LeetCode 2418: Sort the People

LeetCode 2418 Solution Explanation

Explanation

To solve this problem, we need to sort the names array based on the corresponding heights array in descending order. We can achieve this by creating a custom comparator that compares the heights of the people. Then we sort the names array using this comparator.

  1. Create a custom comparator that compares the heights in descending order.
  2. Sort the names array using the custom comparator.

Time Complexity: O(n log n)
Space Complexity: O(n)

LeetCode 2418 Solutions in Java, C++, Python

import java.util.*;

class Solution {
    public String[] sortPeople(String[] names, int[] heights) {
        Integer[] indices = new Integer[heights.length];
        for (int i = 0; i < heights.length; i++) {
            indices[i] = i;
        }
        Arrays.sort(indices, (a, b) -> heights[b] - heights[a]);

        String[] sortedNames = new String[names.length];
        for (int i = 0; i < names.length; i++) {
            sortedNames[i] = names[indices[i]];
        }

        return sortedNames;
    }
}

Interactive Code Editor for LeetCode 2418

Improve Your LeetCode 2418 Solution

Use the editor below to refine the provided solution for LeetCode 2418. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems