Sort the People (LeetCode 2418): Solution and Explanation
Each person has a name and a distinct height. Return the names ordered from the tallest person to the shortest.
Intuition
The heights decide the order and they are all different, so there is exactly one correct answer.
Names can repeat, so a map from name to height breaks on inputs like two people called Bob. The safe link between a name and its height is the shared index i.
Sort the indices by height, tallest first, then read off the names in that order. Every name travels with its own index, so duplicates are no problem.
Approach: Sort indices by height
- Build
order = [0, 1, ..., n - 1]. - Sort
orderso thatheights[order[0]]is the largest and heights decrease from there. - Create
resultby takingnames[i]for eachiinorder. - Return
result.
Step-by-step example
names = ["Mary","John","Emma"], heights = [180,165,170]
- order starts as [0,1,2].
- Sorted by height descending: index 0 (180), index 2 (170), index 1 (165), so order = [0,2,1].
- Read names: Mary, then Emma, then John.
- Return ["Mary","Emma","John"].
Code: Python, Java, C++
1class Solution:
2 def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
3 order = list(range(len(names)))
4 order.sort(key=lambda i: heights[i], reverse=True)
5 result = []
6 for i in order:
7 result.append(names[i])
8 return result1class Solution {
2 public String[] sortPeople(String[] names, int[] heights) {
3 Integer[] order = new Integer[names.length];
4 for (int i = 0; i < names.length; i++) {
5 order[i] = i;
6 }
7 Arrays.sort(order, (a, b) -> heights[b] - heights[a]);
8 String[] result = new String[names.length];
9 for (int k = 0; k < order.length; k++) {
10 result[k] = names[order[k]];
11 }
12 return result;
13 }
14}1class Solution {
2public:
3 vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
4 vector<int> order(names.size());
5 iota(order.begin(), order.end(), 0);
6 sort(order.begin(), order.end(), [&](int a, int b) { return heights[a] > heights[b]; });
7 vector<string> result;
8 for (int i : order) {
9 result.push_back(names[i]);
10 }
11 return result;
12 }
13};Time and space complexity
O(n log n)
One comparison sort over n indices; building the result is O(n).
O(n)
The index array and the result each hold n entries.
Other approaches
Map height to name (time O(n log n), space O(n))
Since heights are distinct they can be keys: store height -> name, sort the heights descending and look each one up. Works here only because heights never repeat.
Sort (height, name) pairs (time O(n log n), space O(n))
Zip the arrays into pairs, sort by height descending and keep the names. Same idea as sorting indices, written with tuples.
Counting by height (time O(n + H), space O(H))
Heights are at most 10^5, so a bucket array indexed by height can hold each name; scan it from the top. Linear in n plus the height range.
Common mistakes
- Using a name-to-height map. Example 2 has two people named Bob, and the map keeps only one of them.
- Sorting ascending and forgetting to reverse. The answer goes from tallest to shortest.
- Sorting names and heights separately, which breaks the pairing between a name and its height.
- Comparators that subtract can overflow in general; here heights are at most 10^5, so heights[b] - heights[a] is safe.
Frequently asked questions
Why sort indices instead of names?
An index is a unique handle for one person, so it carries both the name and the height. Sorting names directly would lose which height belongs to which name.
Does the sort need to be stable?
No. Stability only matters when keys tie, and all heights are distinct, so every comparison has a clear winner.
Can this be done faster than O(n log n)?
With heights bounded by 10^5, a counting approach indexed by height runs in O(n + 10^5). For n up to 1000, sorting is simpler and just as fast in practice.