Sort the People - Problem
Sort the People

Imagine you're organizing a lineup for a group photo! You have a list of people's names and their corresponding heights, and you need to arrange them in descending order by height (tallest to shortest).

You are given:
• An array of strings names where each element is a person's name
• An array of integers heights where each element is the corresponding person's height
• Both arrays have the same length n
• All heights are distinct positive integers

Goal: Return the names array sorted in descending order by the people's heights.

Example: If we have names = ["Mary", "John", "Emma"] and heights = [180, 165, 170], the result should be ["Mary", "Emma", "John"] because Mary (180cm) is tallest, then Emma (170cm), then John (165cm).

Input & Output

example_1.py — Basic Case
$ Input: names = ["Mary", "John", "Emma"], heights = [180, 165, 170]
Output: ["Mary", "Emma", "John"]
💡 Note: Mary is tallest (180cm), then Emma (170cm), then John (165cm). Result is sorted in descending order by height.
example_2.py — Single Person
$ Input: names = ["Alice"], heights = [155]
Output: ["Alice"]
💡 Note: With only one person, the result is just that person's name.
example_3.py — Already Sorted
$ Input: names = ["Tom", "Jerry", "Mickey"], heights = [190, 180, 170]
Output: ["Tom", "Jerry", "Mickey"]
💡 Note: The names are already in correct order since heights are already in descending order.

Constraints

  • n == names.length == heights.length
  • 1 ≤ n ≤ 103
  • 1 ≤ names[i].length ≤ 20
  • 1 ≤ heights[i] ≤ 105
  • names[i] consists of lower and upper case English letters
  • All heights[i] are distinct

Visualization

Tap to expand
📸 Sort the People - Photo LineupRandom OrderAlice 175cmBob 185cmCarol 165cm⚡ Sorting MagicSort by height descendingSorted LineupBob 185cmAlice 175cmCarol 165cm🎯 Algorithm Steps1. Create (height, name) pairs: [(175, "Alice"), (185, "Bob"), (165, "Carol")]2. Sort pairs by height descending: [(185, "Bob"), (175, "Alice"), (165, "Carol")]3. Extract names from sorted pairs: ["Bob", "Alice", "Carol"]Time: O(n log n) | Space: O(n) | Perfect for photo lineups! 📸
Understanding the Visualization
1
Gather People
Collect all people with their names and heights
2
Create Pairs
Pair each person's name with their height
3
Sort by Height
Arrange pairs from tallest to shortest
4
Final Lineup
Extract names in the correct order
Key Takeaway
🎯 Key Insight: Pairing related data together (height with name) makes sorting intuitive and lets us leverage efficient built-in sorting algorithms. This approach is both optimal and highly readable!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
125.0K Views
Medium Frequency
~8 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen