EasyNo. 2418
Sort the People — LeetCode 2418 Python Solution
- Pattern
- Sorting
- Topics
- Array, Hash Table, String, Sorting
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.
Example
- Input
- names = ["Mary","John","Emma"], heights = [180,165,170]
- Output
- ["Mary","Emma","John"]
- Explanation
- Mary is the tallest, followed by Emma and John.
Python solution
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]Complexity
- Time
- O(n × log n)
- Space · auxiliary
- O(n)
Pattern: Sorting
Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2418. Sort the People is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.
The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0049 | Group Anagrams | Medium |
| 0522 | Longest Uncommon Subsequence II | Medium |
| 0692 | Top K Frequent Words | Medium |
| 0720 | Longest Word in Dictionary | Medium |
| 0721 | Accounts Merge | Medium |
| 0792 | Number of Matching Subsequences | Medium |
Frequently asked questions
- How hard is LeetCode 2418. Sort the People?
LeetCode 2418. Sort the People is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2418. Sort the People?
The Python solution on this page runs in O(n × log n).
- What is the space complexity of LeetCode 2418. Sort the People?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2418. Sort the People cover?
LeetCode 2418. Sort the People is tagged Array, Hash Table, String and Sorting on LeetCode.