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
then the output will be
To solve this, we will follow these steps:
Let us see the following implementation to get better understanding:
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))
[[2, 2],[4, 0],[5, 0]]
[[4, 0], [5, 0], [2, 2]]