#2418

Sort the People

Easy
ArrayHash TableStringSortingSortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages sorting to efficiently arrange names based on heights. This is like organizing a list of books by height using a library's sorting system.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of tuples pairing each name with its corresponding height.
  2. 2Step 2: Sort this list of tuples based on the height in descending order.
  3. 3Step 3: Extract the names from the sorted list and return them.
solution.py4 lines
1def sortPeople(names, heights):
2    people = list(zip(heights, names))
3    people.sort(reverse=True)
4    return [name for height, name in people]

Complexity note: This complexity is due to the sorting step, which is more efficient than the nested loops used in the brute-force approach.

  • 1Sorting can drastically reduce the complexity of the problem compared to finding maximums repeatedly.
  • 2Using data structures like tuples or pairs can simplify the association between names and heights.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.