Menu Close

Leetcode 2418: Sort the People Solution

Here, we will see how to solve sort the People Solution of leet code 2418 problem with code and algorithm.

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 inames[i] and heights[i] denote the name and height of the ith person.

You have to return names sorted in descending order by the people’s heights.

Example:

1)
Input: names = ["John","Alice","Bob"], heights = [181,166,172]
Output: ["John","Bob","Alice"]
Explanation: John is the tallest, followed by Bob and Alice.

2)
Input: names = ["Alice","Bob","Bob"], heights = [155,185,150]
Output: ["Bob","Alice","Bob"]
Explanation: The first Bob is the tallest, followed by Alice and the second Bob.

Sort the People Solution code in C++

Code 1:

#include <iostream>
#include <vector>
#include <map>

using namespace std;

vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
    // Map will store data in descending oerder based on height
    map<int, string, greater<int> > m;
    vector<string> v;
        
    for(int i = 0; i < names.size(); i++) {
        m[heights[i]] = names[i];
    }
    
    // Store names in descending order in vector
    for(auto it : m) {
        v.push_back(it.second);
    }
    return v;
}

int main()
{
    vector<string> names = {"John","Alice","Bob"};
    vector<int> heights = {181,166,172};
    
    vector<string> v = sortPeople(names, heights);
    
    for(auto it : v) {
        cout<<it<<"\n";
    }

    return 0;
}

Code 2:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using namespace std;

bool cmp(pair<int, string> a, pair<int, string> b) {
    return a.first > b.first ? true : false;
}

vector<string> sortPeople(vector<string>& names, vector<int>& heights) {
    vector<pair<int, string> > v;
        
    // Store heights and namess in vector respectively
    for(int i = 0; i < names.size(); i++) {
        v.push_back(make_pair(heights[i], names[i]));
    }
    
    // Sort the vector in decending order of heights
    sort(v.begin(), v.end(), cmp);
    
    vector<string> res;
    
    // Store only names in result vector
    for(auto it : v) {
        res.push_back(it.second);
    }
    return res;
}

int main()
{
    vector<string> names = {"John","Alice","Bob"};
    vector<int> heights = {181,166,172};
    
    vector<string> v = sortPeople(names, heights);
    
    for(auto it : v) {
        cout<<it<<"\n";
    }

    return 0;
}

Output:

John
Bob
Alice

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, Leetcode

Leave a Reply

Your email address will not be published.

Contact Us