Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Greedy

Queue Reconstruction by Height

Medium · Greedy · Asked at Google, Amazon, Microsoft

People stood in a queue. For each person you know h (their height) and k (how many people in front of them have a height ≥ h). The list below is in a random order. Rebuild the queue and print it from front to back, one h k per line.

Input

First line: n. Next n lines: h k.

Output

n lines: the queue from front to back.

Constraints

Place the tallest people first: sort by height descending (and k ascending for equal heights), then insert each person at index k. Everyone already placed is at least as tall, so k counts exactly the people in front, and shorter people inserted later never affect it.

Example 1

Input

6
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

Example 2

Input

6
6 0
5 0
4 0
3 2
2 2
1 4

Output

4 0
5 0
2 2
3 2
1 4
6 0

Hints

  1. Shorter people are invisible to a taller person’s k.
  2. So place the tallest people first — their k is just their index among themselves.
  3. Then insert each shorter person at index k: everyone already placed is at least as tall.

Approach

Sort by height descending, and by k ascending among equal heights. Insert each person into a list at position k. When a person is inserted, exactly k people already in front are at least as tall (all placed people are), and people inserted later are shorter, so they never change anyone's count. Inserting into a list costs O(n) per person.

Complexity: O(n²) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<pair<int, int>> p(n);
    for (auto &x : p) cin >> x.first >> x.second;
    sort(p.begin(), p.end(), [](auto &a, auto &b) { return a.first != b.first ? a.first > b.first : a.second < b.second; });
    vector<pair<int, int>> q;
    for (auto &x : p) q.insert(q.begin() + x.second, x);
    for (auto &x : q) cout << x.first << " " << x.second << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
people = sorted(((data[1 + 2 * i], data[2 + 2 * i]) for i in range(n)), key=lambda x: (-x[0], x[1]))
q = []
for h, k in people:
    q.insert(k, (h, k))
print("\n".join(f"{h} {k}" for h, k in q))

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        int[][] p = new int[n][2];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            p[i][0] = (int) in.nval;
            in.nextToken();
            p[i][1] = (int) in.nval;
        }
        Arrays.sort(p, (a, b) -> a[0] != b[0] ? Integer.compare(b[0], a[0]) : Integer.compare(a[1], b[1]));
        List<int[]> q = new ArrayList<>();
        for (int[] x : p) q.add(x[1], x);
        StringBuilder sb = new StringBuilder();
        for (int[] x : q) sb.append(x[0]).append(' ').append(x[1]).append('\n');
        System.out.print(sb);
    }
}

Solve Queue Reconstruction by Height online · All practice problems