Validating push pop sequence in JavaScript


Problem

JavaScript function that takes in two arrays, pushed and popped, as the first and the second argument. Both these arrays are guaranteed to consist of unique elements.

Our function should return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack, false otherwise.

For example, if the input to the function is −

const pushed = [1, 2, 3, 4, 5];
const popped = [4, 5, 3, 2, 1];

Then the output should be −

const output = true;

Output Explanation

We might do the following sequence −

push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example

The code for this will be −

 Live Demo

const pushed = [1, 2, 3, 4, 5];
const popped = [4, 5, 3, 2, 1];
const validateSequence = (pushed = [], popped = []) => {
   let pushedIndex = 0
   let poppedIndex = 0
   const stack = []
   while (pushedIndex < pushed.length) {
      if (stack[stack.length - 1] !== popped[poppedIndex]) {
         stack.push(pushed[pushedIndex++])
      } else {
         stack.pop()
         poppedIndex += 1
      }
   }
   while (stack.length) {
      if (stack.pop() !== popped[poppedIndex++]) {
         return false
      }
   }
   return true;
};
console.log(validateSequence(pushed, popped));

Output

And the output in the console will be −

true

Updated on: 09-Apr-2021

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements