Sort the People
Problem
You are given an array of names and an array of heights, where the person at index i is named names[i] and stands heights[i] tall. Every height is distinct. Return the names ordered so that the tallest person comes first and the shortest comes last (descending by height).
names = ["Mary", "John", "Emma"], heights = [180, 165, 170]["Mary", "Emma", "John"]def sort_people(names, heights):
people = list(zip(heights, names))
people.sort(reverse=True)
result = []
for height, name in people:
result.append(name)
return result
function sortPeople(names, heights) {
const people = names.map((name, i) => [heights[i], name]);
people.sort((a, b) => b[0] - a[0]);
const result = [];
for (const [height, name] of people) {
result.push(name);
}
return result;
}
class Solution {
public String[] sortPeople(String[] names, int[] heights) {
Integer[] idx = new Integer[names.length];
for (int i = 0; i < names.length; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> heights[b] - heights[a]);
String[] result = new String[names.length];
for (int i = 0; i < idx.length; i++) result[i] = names[idx[i]];
return result;
}
}
vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
vector<pair<int, string>> people;
for (int i = 0; i < (int)names.size(); i++) people.push_back({heights[i], names[i]});
sort(people.rbegin(), people.rend());
vector<string> result;
for (auto& p : people) result.push_back(p.second);
return result;
}
Explanation
The two arrays are really one table split into columns: names[i] and heights[i] describe the same person. The danger is sorting the heights on their own — then the heights would line up neatly but the names would no longer point at the right people.
The fix is to keep each name glued to its height. We pair them up as (height, name) tuples so that whenever a pair moves during the sort, the name travels with it.
Now we sort those pairs by height in descending order (tallest first). Because the names ride along, the pairs come out in the exact order we want.
Finally we walk the sorted pairs and collect just the name from each, dropping the height we only needed for ordering.
Example: (180, Mary), (165, John), (170, Emma) sort by height to (180, Mary), (170, Emma), (165, John), and reading off the names gives ["Mary", "Emma", "John"].