You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
For each index i, names[i] and heights[i] denote the name and height of the i-th person.
Return 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"]Explanation: Mary is the tallest, followed by Emma and John.
Example 2:
Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]Explanation: The first Bob is the tallest, followed by Alice and the second Bob.
Constraints:
n == names.length == heights.length1 <= n <= 10001 <= names[i].length <= 201 <= heights[i] <= 100,000names[i] consists of lower and upper case English letters.heights are distinct.Before attempting this problem, you should be comfortable with:
Since all heights are distinct, we can use each height as a unique key to look up the corresponding person's name. By building a hash map from height to name, we can then sort the heights in descending order and retrieve names in the correct sequence.
heights array in ascending order.res.res array containing names sorted by height in descending order.class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
height_to_name = {}
for h, n in zip(heights, names):
height_to_name[h] = n
res = []
for h in reversed(sorted(heights)):
res.append(height_to_name[h])
return resInstead of using a hash map, we can pair each height with its corresponding name directly. By creating an array of (height, name) pairs and sorting them by height in descending order, we keep the relationship intact throughout the sorting process.
(height, name).class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
arr = list(zip(heights, names))
arr.sort(reverse=True)
return [name for _, name in arr]Rather than copying data into pairs, we can sort an array of indices based on the heights they point to. This approach is memory efficient when names are long strings, since we only move integers during sorting rather than entire strings.
0 to n-1.indices array using a custom comparator that compares the heights at those indices in descending order.class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
indices = list(range(len(names)))
indices.sort(key=lambda i: -heights[i])
return [names[i] for i in indices]The problem asks for people sorted by height in descending order (tallest first). A common mistake is to sort in ascending order and forget to reverse the result or adjust the comparator.
When sorting heights separately from names, you must maintain a way to retrieve the corresponding name for each height. Using a hash map or pairing heights with indices before sorting prevents this association from being lost.
Sign in to join the discussion