Sort the People - Complete Solution Guide
Sort the People is LeetCode problem 2418, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 i th 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"
Detailed Explanation
The problem asks you to sort an array of names based on the corresponding heights provided in another array. Both arrays have the same length, and the heights are unique. The output should be the names sorted in descending order of their corresponding heights. For example, if `names = ["Mary", "John", "Emma"]` and `heights = [180, 165, 170]`, the output should be `["Mary", "Emma", "John"]` because Mary is the tallest (180), followed by Emma (170), and then John (165).
Solution Approach
The provided solutions utilize different approaches to solve the problem. The Python and C++ solutions create pairs of (height, name) and then sort these pairs in descending order based on the height. The Java solution uses a HashMap to map heights to names, sorts the heights array, and then retrieves names based on the sorted heights. The C solution implements a custom sorting algorithm using an array of indices to track the original order of names.
Step-by-Step Algorithm
- Step 1: Create a data structure to associate names and heights. This could be pairs (Python, C++), a HashMap (Java), or an index array (C).
- Step 2: Sort the data structure based on heights in descending order.
- Step 3: Extract the names from the sorted data structure and return them as the result.
Key Insights
- Insight 1: The problem requires pairing names with heights to maintain the correct association during sorting.
- Insight 2: Sorting algorithms (like merge sort or quicksort) are crucial for efficient sorting of the paired data.
- Insight 3: Utilizing data structures that facilitate efficient pairing and sorting (e.g., pairs, maps) is key to an optimal solution.
Complexity Analysis
Time Complexity: O(n log n)
Space Complexity: O(n)
Topics
This problem involves: Array, Hash Table, String, Sorting.
Companies
Asked at: Infosys.