LeetCode 2418: Sort the People Solution
Master LeetCode problem 2418 (Sort the People), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2418. Sort the People
Problem 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.
- Create a custom comparator that compares the heights in descending order.
- Sort the names array using the custom comparator.
Time Complexity: O(n log n)
Space Complexity: O(n)
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2418 (Sort the People)?
This page provides optimized solutions for LeetCode problem 2418 (Sort the People) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2418 (Sort the People)?
The time complexity for LeetCode 2418 (Sort the People) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2418 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2418 in Java, C++, or Python.