Queue Reconstruction by Height in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 has a height greater than or equal to h.

We have to write an algorithm to reconstruct the queue.

Note − The number of people is less than 1,100.

For example − If the input queue is −

const arr = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]];

Then the output queue should be −

const output = [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]];

Example

The code for this will be −

const arr = [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]];
const reconstructQueue = data => {
   const result = [];
   const sorter = (a, b) => {
      return b[0] - a[0] || a[1] - a[1];
   };
   data.sort(sorter);
   for (let i = 0; i < data.length; i++) {
      result.splice(data[i][1], 0, data[i]);
   };
   return result;
};
console.log(reconstructQueue(arr));

Output

And the output in the console will be −

[ [ 5, 0 ], [ 7, 0 ], [ 5, 2 ], [ 6, 1 ], [ 4, 4 ], [ 7, 1 ] ]
raja
Updated on 25-Nov-2020 06:59:40

Advertisements