Skip to content

2418. Sort the People 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
    vector<string> ans;
    vector<pair<int, string>> heightAndNames;

    for (int i = 0; i < names.size(); ++i)
      heightAndNames.emplace_back(heights[i], names[i]);

    ranges::sort(heightAndNames, greater<>());

    for (const auto& [_, name] : heightAndNames)
      ans.push_back(name);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public String[] sortPeople(String[] names, int[] heights) {
    List<Pair<Integer, String>> heightAndNames = new ArrayList<>();

    for (int i = 0; i < names.length; ++i)
      heightAndNames.add(new Pair<>(heights[i], names[i]));

    Collections.sort(heightAndNames, (a, b) -> b.getKey().compareTo(a.getKey()));

    for (int i = 0; i < heightAndNames.size(); ++i)
      names[i] = heightAndNames.get(i).getValue();

    return names;
  }
}
1
2
3
4
class Solution:
  def sortPeople(self, names: list[str], heights: list[int]) -> list[str]:
    return [height for _, height in
            sorted([(height, name) for name, height in zip(names, heights)], reverse=True)]