# Program to recover shuffled queue of people in python

Suppose we have a 2D matrix where each row contains two values [height, count] these indicates the person has given height and there are 'count' number of people in front of them that are at least as tall as them. Now consider this queue is shuffled, we have to recover the original ordering of the queue.

So, if the input is like

 2 2 4 0 5 0

then the output will be

 4 0 5 0 2 2

To solve this, we will follow these steps:

• N := row count of matrix
• rearrange matrix rows based on increasing height and decreasing count
• ans := make a list of size N and initially all entries are null
• for each height h, and count c in matrix row, do
• temp := 0
• for each index i, and value num ans, do
• if temp >= c and num is null, then
• ans[i] := [h, c]
• come out from the loop
• if num is null or num >= h, then
• temp := temp + 1
• return ans

Let us see the following implementation to get better understanding:

## Example

Live Demo

class Solution:
def solve(self, matrix):
N = len(matrix)
matrix.sort(key=lambda x: [x, -x])
ans = [None] * N

for h, c in matrix:
temp = 0
for i, num in enumerate(ans):
if temp >= c and num is None:
ans[i] = [h, c]
break

if num is None or num >= h:
temp += 1
return ans

ob = Solution()
matrix = [
[2, 2],
[4, 0],
[5, 0]
]
print(ob.solve(matrix))

## Input

[[2, 2],[4, 0],[5, 0]]

## Output

[[4, 0], [5, 0], [2, 2]]