Queue Reconstruction by Height
LeetCode Problem #406 (Medium)
Problem Statement
Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k)
, where h
is the height of the person and k
is the number of people in front of this person who have a height greater than or equal to h
. Write an algorithm to reconstruct the queue.
Testcase
Problem Explanation
In this problem, we are given a two-dimensional vector containing pairs of integers which describe two attributes of a person standing in a queue—height (h) and number of people standing in front of them who are taller than them (k).
Example:
Consider the queue: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
Prerequisite Knowledge
Insertion Sort
This is an in-place comparison-based sorting algorithm where a sorted sub-list is maintained and every consecutive element which is compared must find its appropriate position within the sorted sub-list. In effect, it is as though each element "inserts" itself in the correct position during every iteration.
Algorithm
Insertion Sort Approach
In this approach, we perform in-place sorting by taking two parameters of comparison into consideration.
At each iteration, the first value in the vector, which is the height value, is sorted in descending order since the problem allows for taller people to stand in front of shorter people.
If the height values are equal, we compare the second value in the vector, which is the number of people standing in front of the particular person, in ascending order.
Initialize an empty vector to insert each person.
Compare each person such that
a. If they do not have the same height (h) value, they should be sorted in descending order.
b. If they have the same height (h) value, sort them in ascending order of the number of people in front of them (k).
Insert each person into position k.
Illustration
In the first pass, we consider the first vector [7, 1]. The first element is considered to be sorted already, so we place it at position 0.
In the second pass, we look for a vector with a h value less than 7 in order to sort in descending order. We take vector [7, 0], but since the h value is the same as vector [7, 1], we consider the k value and sort in ascending order, placing [7, 1] at position 1.
In the third pass, we choose vector [6, 1] and place it at position 1.
In the fourth pass, we choose vector [5, 0] and place it at position 0.
In the fifth pass, we choose vector [5, 2] and place it at position 2.
In the final pass, we chose vector [4, 4] and place it at position 4 to obtain the final output.
Code
Last updated
Was this helpful?