We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Sort the People

Number: 2502

Difficulty: Easy

Paid? No

Companies: Google, Meta, Bloomberg, Apple, Adobe, Uber, Infosys


Problem Description

You are given two arrays, names and heights, both of the same length. For each index i, names[i] is the name of the iᵗʰ person and heights[i] is that person's height. All values in heights are distinct. The goal is to return the names sorted in descending order by their corresponding heights.


Key Insights

  • Pair each name with its corresponding height.
  • Use sorting to order the pairs by height in descending order.
  • Extract the sorted names from the ordered pairs.

Space and Time Complexity

Time Complexity: O(n log n) due to the sorting step. Space Complexity: O(n) for storing the combined pairs of names and heights.


Solution

The solution involves pairing the names with their corresponding heights, sorting these pairs in descending order based on the heights, and then extracting the names from the sorted pairs. This approach leverages the efficiency of built-in sorting algorithms and simple data structures like arrays and lists.


Code Solutions

def sortPeople(names, heights):
    # Pair names with their corresponding heights
    paired_list = list(zip(names, heights))
    # Sort the pairs by height in descending order
    sorted_pairs = sorted(paired_list, key=lambda x: x[1], reverse=True)
    # Extract and return the sorted names
    return [name for name, height in sorted_pairs]

# Example usage
names = ["Mary", "John", "Emma"]
heights = [180, 165, 170]
print(sortPeople(names, heights))  # Output: ['Mary', 'Emma', 'John']
← Back to All Questions