Sort the People - 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.

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.

Input & Output

Example 1 — Basic Sorting
$ Input: names = ["Mary","John","Emma"], heights = [180,165,170]
Output: ["Mary","Emma","John"]
💡 Note: Mary is tallest (180), Emma is second (170), John is shortest (165). Sorted in descending order by height.
Example 2 — Different Names
$ Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
💡 Note: Bob (185) is tallest, Alice (155) is middle, Bob (150) is shortest. Names can repeat but heights are distinct.
Example 3 — Two People
$ Input: names = ["IEO","Sgizfdfrims"], heights = [165,170]
Output: ["Sgizfdfrims","IEO"]
💡 Note: Sgizfdfrims (170) is taller than IEO (165), so comes first in descending order.

Constraints

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

Visualization

Tap to expand
Sort the People - Direct Pair Sorting INPUT names array: "Mary" "John" "Emma" i=0 i=1 i=2 heights array: 180 165 170 Paired Data: Mary 180cm John 165cm Emma 170cm n = 3 people ALGORITHM STEPS 1 Create Pairs Combine name + height [(180,"Mary"), (165,"John"), (170,"Emma")] 2 Sort by Height Descending order (high-low) [(180,"Mary"), (170,"Emma"), (165,"John")] 3 Extract Names Get names from sorted pairs result = ["Mary","Emma","John"] 4 Return Result O(n log n) time complexity FINAL RESULT Sorted by height (descending): Mary - 180cm (Tallest) Emma - 170cm John - 165cm Output Array: ["Mary","Emma","John"] Verification - OK 180 > 170 > 165 Order is correct! Key Insight: Direct Pair Sorting pairs each name with its corresponding height, then sorts these pairs by height in descending order. This maintains the name-height relationship during sorting. Finally, we extract just the names from the sorted pairs. Time: O(n log n) for sorting, Space: O(n) for storing pairs. TutorialsPoint - Sort the People | Direct Pair Sorting Approach
Asked in
Amazon 15 Microsoft 12 Google 8
25.0K Views
Medium Frequency
~5 min Avg. Time
892 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