Queue Reconstruction by Height in C++


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

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements