← Home

406. Queue Reconstruction by Height

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
406

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 406. Queue Reconstruction by Height, the solution in this repository is mainly a greedy solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • Hint 1: What can you say about the position of the shortest person?
  • If the position of the shortest person is i, how many people would be in front of the shortest person?
  • Hint 2: Once you fix the position of the shortest person, what can you say about the position of the second shortest person?

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are filled.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Hint 1: What can you say about the position of the shortest person?
02//If the position of the shortest person is i, how many people would be in front of the shortest person?
03//Hint 2: Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
04
05//Runtime: 92 ms, faster than 44.28% of C++ online submissions for Queue Reconstruction by Height.
06//Memory Usage: 11.5 MB, less than 100.00% of C++ online submissions for Queue Reconstruction by Height.
07
08class Solution {
09public:
10    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
11        int N = people.size();
12        vector<vector<int>> ans(N);
13        vector<bool> filled(N, false);
14        
15        sort(people.begin(), people.end(), [](const vector<int>& a, const vector<int>& b){return (a[0] == b[0]) ? (a[1] < b[1]) : (a[0] < b[0]);});
16        
17        for(int i = 0; i < N; i++){
18            int value =  people[i][0], largerCount = people[i][1];
19            // cout << "value & count: " << value << " " << largerCount << endl;
20            //want to find a empty position with j larger values before
21            //so we actually want to find (j+1)th(1-based) position which is empty or has value >= people[i][0]
22            int pos, j;
23            for(pos = 0, j = 0; j <= largerCount; pos++){
24                if(!filled[pos] || (filled[pos] && ans[pos][0] >= value))
25                    j++;
26                // cout << pos << " " << j << endl;
27            }
28            pos--;
29            // cout << pos << " " << j << endl;
30           
31            ans[pos] = people[i];
32            filled[pos] = true;
33        }
34        
35        return ans;
36    }
37};
38
39//https://leetcode.com/problems/queue-reconstruction-by-height/discuss/89345/Easy-concept-with-PythonC%2B%2BJava-Solution
40//construct a subarray an then insert one by one
41//Runtime: 80 ms, faster than 76.98% of C++ online submissions for Queue Reconstruction by Height.
42//Memory Usage: 11.8 MB, less than 100.00% of C++ online submissions for Queue Reconstruction by Height.
43
44class Solution {
45public:
46    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
47        int N = people.size();
48        //need to return empty 2d array for empty input
49        if(N == 0) return vector<vector<int>>();
50        vector<vector<int>> ans;
51        //cannot simply use this?
52        // vector<vector<int>> ans = vector<vector<int>>();
53        
54        //first sort by "h"(descending), and then by "k"(ascending)
55        sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b){return (a[0] == b[0]) ? (a[1] < b[1]) : a[0] > b[0];});
56        
57        int maxh = people[0][0];
58        
59        //create subarray containing people with max height
60        for(int i = 0; i < N; i++){
61            if(people[i][0] == maxh){
62                ans.push_back(people[i]);
63            }else{
64                ans.insert(ans.begin()+people[i][1], people[i]);
65            }
66        }
67        
68        return ans;
69    }
70};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.