Sort the People
EasyPrompt
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 ith 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 <= 1031 <= names[i].length <= 201 <= heights[i] <= 105names[i]consists of lower and upper case English letters.- All the values of
heightsare distinct.
Approaches
3 approaches with complexity analysis and trade-offs.
This approach directly simulates the sorting process without using advanced data structures or sorting algorithms. It repeatedly finds the tallest person among the remaining unsorted people and places their name in the correct position in the result array. This is analogous to a Selection Sort.
Algorithm
-
- Initialize a new string array
resultof sizen.
- Initialize a new string array
-
- Initialize a boolean array
visitedof sizenwith all values asfalse.
- Initialize a boolean array
-
- Loop from
i = 0ton-1: a. InitializemaxIndex = -1andmaxHeight = -1. b. Loop fromj = 0ton-1: i. Ifvisited[j]isfalseandheights[j]is greater thanmaxHeight, updatemaxHeighttoheights[j]andmaxIndextoj. c. Place the name of the found person in the result:result[i] = names[maxIndex]. d. Mark the person as visited:visited[maxIndex] = true.
- Loop from
-
- Return the
resultarray.
- Return the
Walkthrough
The algorithm works as follows:
- We create a result array
sortedNamesto store the final sorted list of names and a boolean arrayvisitedof the same sizento keep track of people who have already been placed in the result. - We then loop
ntimes, once for each position in thesortedNamesarray. - In each iteration of this outer loop, we perform a linear scan through the entire
heightsarray to find the person with the maximum height who has not beenvisitedyet. We keep track of this person's index. - Once the tallest unvisited person is found, we add their name to the current position in the
sortedNamesarray and mark their index asvisited. - This process is repeated until all positions in
sortedNamesare filled. The final array is then returned.
class Solution { public String[] sortPeople(String[] names, int[] heights) { int n = names.length; String[] result = new String[n]; boolean[] visited = new boolean[n]; for (int i = 0; i < n; i++) { int maxHeight = -1; int maxIndex = -1; for (int j = 0; j < n; j++) { if (!visited[j] && heights[j] > maxHeight) { maxHeight = heights[j]; maxIndex = j; } } result[i] = names[maxIndex]; visited[maxIndex] = true; } return result; }}Complexity
Time
O(n^2) - The code has nested loops. The outer loop runs `n` times, and for each iteration, the inner loop also runs `n` times to find the maximum height among the remaining people.
Space
O(n) - We use an additional boolean array `visited` of size `n` and a `result` array of size `n`.
Trade-offs
Pros
Conceptually simple and easy to implement from scratch.
Does not require knowledge of complex data structures or built-in sorting functions.
Cons
Highly inefficient with a time complexity of O(n^2), making it unsuitable for large datasets.
A much more efficient method is to link each name with its height. This can be done by creating a custom data structure (like a Person class) or using a 2D array to hold pairs of (height, name). After creating these pairs, we can use a standard, efficient sorting algorithm to sort the pairs based on height in descending order. Finally, we can iterate through the sorted pairs to construct the final sorted list of names.
Algorithm
-
- Define a helper class or structure (e.g.,
Person) to store a name and a height together.
- Define a helper class or structure (e.g.,
-
- Create an array or list of these
Personobjects,people, of sizen.
- Create an array or list of these
-
- Iterate from
i = 0ton-1, populating thepeoplecollection with(names[i], heights[i]).
- Iterate from
-
- Sort the
peoplecollection in descending order based on theheightattribute using a standard sorting algorithm.
- Sort the
-
- Create a new string array
resultof sizen.
- Create a new string array
-
- Iterate through the sorted
peoplecollection and populate theresultarray with the names.
- Iterate through the sorted
-
- Return the
resultarray.
- Return the
Walkthrough
This approach involves three main steps:
- Pairing: We create a custom class, say
Person, to encapsulate thenameandheightof an individual. We then iterate through the input arrays and create an array ofPersonobjects, where each objectpeople[i]corresponds tonames[i]andheights[i]. - Sorting: We use a built-in sorting function, such as
Arrays.sort()in Java. We provide a custom comparator that instructs the sort function to arrange thePersonobjects in descending order based on theirheightattribute. This step is the core of the approach and is typically very efficient (O(n log n)). - Extraction: After the
peoplearray is sorted, we create a new string array for the result. We then iterate through the sortedpeoplearray and extract thenamefrom eachPersonobject, placing it into our result array.
class Solution { class Person { String name; int height; Person(String name, int height) { this.name = name; this.height = height; } } public String[] sortPeople(String[] names, int[] heights) { int n = names.length; Person[] people = new Person[n]; for (int i = 0; i < n; i++) { people[i] = new Person(names[i], heights[i]); } // Sort in descending order of height Arrays.sort(people, (a, b) -> b.height - a.height); String[] result = new String[n]; for (int i = 0; i < n; i++) { result[i] = people[i].name; } return result; }}Complexity
Time
O(n log n) - The dominant operation is sorting the array of pairs. Creating the pairs and extracting the names are both O(n) operations.
Space
O(n) - We need an auxiliary array of size `n` to store the `Person` objects.
Trade-offs
Pros
Significantly more efficient (O(n log n)) than the brute-force approach.
A general and common pattern for sorting related data.
Relatively easy to implement using built-in sorting utilities.
Cons
Requires extra space (O(n)) to store the pairs.
Involves creating a helper class or structure, which adds a bit of boilerplate code.
This approach leverages a map data structure to associate heights with names. Since all heights are distinct, they can serve as unique keys. By using a sorted map, such as a TreeMap in Java, we can automatically maintain the people in sorted order by height. This leads to a very clean and concise solution.
Algorithm
-
- Create a
TreeMapthat mapsIntegerkeys (heights) toStringvalues (names). Initialize it with a comparator for descending order.
- Create a
-
- Iterate from
i = 0ton-1and insert each(heights[i], names[i])pair into the map.
- Iterate from
-
- The
TreeMapautomatically maintains the entries sorted by key in descending order.
- The
-
- Retrieve the collection of values (names) from the map. This collection will be in the correct sorted order.
-
- Convert the collection of values to a string array and return it.
Walkthrough
The core idea is to use the heights as keys and names as values in a map. A TreeMap is ideal because it keeps its keys sorted.
- We instantiate a
TreeMapand provide it with a reverse order comparator (Collections.reverseOrder()). This ensures that as we add entries, the map will automatically sort them by key (height) in descending order. - We iterate through the input arrays once, from
i = 0ton-1. In each iteration, we insert a key-value pair(heights[i], names[i])into theTreeMap. - After the loop finishes, the
TreeMapcontains all the people, sorted by height from tallest to shortest. - The
values()collection of theTreeMapwill now provide the names in the desired sorted order. We can simply convert this collection to an array and return it.
import java.util.Map;import java.util.TreeMap;import java.util.Collections; class Solution { public String[] sortPeople(String[] names, int[] heights) { int n = names.length; Map<Integer, String> map = new TreeMap<>(Collections.reverseOrder()); for (int i = 0; i < n; i++) { map.put(heights[i], names[i]); } return map.values().toArray(new String[0]); }}Complexity
Time
O(n log n) - Inserting `n` elements into a `TreeMap` takes O(n log n) time, as each insertion is an O(log k) operation where `k` is the current size of the map. Retrieving the values is an O(n) operation.
Space
O(n) - The `TreeMap` needs to store `n` key-value pairs.
Trade-offs
Pros
Very elegant and concise code.
Effectively uses built-in data structures to handle the sorting logic implicitly.
Avoids the need for a custom helper class.
Cons
The performance might have a slightly higher constant factor overhead compared to sorting a simple array of custom objects, depending on the
TreeMapimplementation.
Solutions
Solution
class Solution { public String [] sortPeople ( String [] names , int [] heights ) { int n = names . length ; Integer [] idx = new Integer [ n ]; for ( int i = 0 ; i < n ; ++ i ) { idx [ i ] = i ; } Arrays . sort ( idx , ( i , j ) -> heights [ j ] - heights [ i ]); String [] ans = new String [ n ]; for ( int i = 0 ; i < n ; ++ i ) { ans [ i ] = names [ idx [ i ]]; } return ans ; } }class Solution { public: vector < string > sortPeople ( vector < string >& names , vector < int >& heights ) { int n = names . size (); vector < int > idx ( n ); iota ( idx . begin (), idx . end (), 0 ); sort ( idx . begin (), idx . end (), [ & ]( int i , int j ) { return heights [ j ] < heights [ i ]; }); vector < string > ans ; for ( int i : idx ) { ans . push_back ( names [ i ]); } return ans ; } };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 ]Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.