- Notifications
You must be signed in to change notification settings - Fork0
Hasheditz/Leetcode-CSES-GFG-Codeforces-Coding-Solutions
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Editorial for the Problem:Sort the People
The problem is to sort a list of people by their heights in descending order. Given two lists,nam
(names) andh
(heights), we aim to produce a sorted list of names based on their corresponding heights.
To solve this problem efficiently, we can use the following approach:
Pairing Names with Heights:
- Create a vector of pairs where each pair consists of a height and the corresponding name.
Sorting the Pairs:
- Sort the vector of pairs in descending order based on heights.
Extracting the Sorted Names:
- Extract the names from the sorted pairs into the result vector.
Create Pairs:
- Pair each name with its corresponding height.
Sort the Pairs:
- Sort the pairs in descending order by height using the built-in sort function.
Construct the Result:
- Construct the final sorted list of names from the sorted pairs.
classSolution {public: vector<string>sortPeople(vector<string>& nam, vector<int>& h) {int n = h.size(); vector<string> ans; vector<pair<int, string>> res;for (int i =0; i < n; i++) { res.push_back({h[i], nam[i]}); }sort(res.rbegin(), res.rend());for (auto i : res) { ans.push_back(i.second); }return ans; }};
Pairing Names with Heights:
- A vector of pairs
res
is created, where each pair contains a height and the corresponding name. - We iterate over the indices of the input lists and push the pairs into
res
.
Sorting the Pairs:
- The vector
res
is sorted in descending order by height usingsort(res.rbegin(), res.rend());
. This sorts the pairs based on the first element of each pair, which is the height.
Constructing the Result:
- After sorting, we iterate through the sorted pairs and extract the names, pushing them into the result vector
ans
.
The time complexity is dominated by the sorting operation, which is ( O(n log n) ), where ( n ) is the number of people. The space complexity is ( O(n) ) due to the storage of pairs and the result vector.
If you found this solution helpful, please consider liking 👍 and upvoting ⬆️. Your support helps in continuing to provide high-quality solutions.
About
Here you all find all my solutions of the Leetcode, CSES, GFG, CodeForces with some more DSA Question
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.