Given two lists names
and heights
of the same length n
, where names[i]
is the name of the ith person and heights[i]
is the height of the ith person, return the names sorted in descending order by the people’s heights.
Example 1:
Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
Example 2:
Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Constraints:
n == names.length == heights.length
1 <= n <= 100
1 <= heights[i] <= 10^5
names[i]
consists of alphabets.names
and heights
lists together to create pairs of (name, height).Here’s a Python implementation for the problem:
def sortPeople(names, heights):
# Zip the names and heights together
people = list(zip(names, heights))
# Sort the zipped list by height in descending order
people.sort(key=lambda x: x[1], reverse=True)
# Extract the sorted names
sorted_names = [person[0] for person in people]
return sorted_names
This solution is efficient given the problem constraints. The space complexity is linear relative to the input size, and the time complexity is optimal for sorting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?