# Queue Reconstruction by Height in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Consider we have a random list of people standing in a queue. If each person is described by a pair of integers (h, k), where h is the height and k is the number of people in front of him, who have a height greater than or equal to h. We have to define one method to reconstruct the queue. So if the given array is like [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]], then the output will be [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

To solve this, we will follow these steps −

• sort the given array based on the following comparison strategy
• if a[0] = b[0], then return a[1] > b[1], otherwise return a[0] < b[0]
• create one vector called ans
• for i in range size of given array down to 0
• insert (first element of ans + p[i, 1], p[i]) into ans array
• return ans

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
bool cmp(vector <int> a, vector <int> b){
if(a[0] == b[0])return a[1] > b[1];
return a[0] < b[0];
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& p) {
sort(p.begin(), p.end(), cmp);
vector < vector <int> > ans;
for(int i = p.size()-1; i>=0; i--){
ans.insert(ans.begin() + p[i][1], p[i]);
}
return ans;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{7,0}, {4,4}, {7,1}, {5,0}, {6,1}, {5,2}};
print_vector(ob.reconstructQueue(v));
}

## Input

[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

## Output

[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
Updated on 28-Apr-2020 12:23:17