Sort the People Problem
#2418
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2418.
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 <= 10^31 <= names[i].length <= 201 <= heights[i] <= 10^5names[i]consists of lower and upper case English letters.- All the values of
heightsare distinct.
Solution
Approach: Sorting
Sort the indices 0..n-1 by their height in descending order, then output names[i] for each index in that order. Heights are distinct, so the order is unambiguous.
Complexity: O(n log n) time and O(n) extra space.
class Solution:
def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:
idx = list(range(len(heights)))
idx.sort(key=lambda i: -heights[i])
return [names[i] for i in idx]