# LeetCode: Validate Stack Sequences Solution

## Approach

Push value to stack

Along with that, keep pop stack if its top is equal to the first element of the popped array (also shift the popped array in that case)

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}function Stack() {2  const stack = []3
4  this.push = function (el) {5    stack.push(el)6  }7
8  this.pop = function () {9    return stack.pop()10  }11
12  this.peek = function () {13    return stack[stack.length - 1]14  }15
16  this.isEmpty = function () {17    return stack.length === 018  }19}20
21/**22 * @param {number[]} pushed23 * @param {number[]} popped24 * @return {boolean}25 */26var validateStackSequences = function (pushed, popped) {27  const N = pushed.length28  const stack = new Stack()29  let i = 030  let j = 031  while (i < N) {32    stack.push(pushed[i++])33    while (stack.peek() === popped[j] && j < N) {34      stack.pop()35      j++36    }37  }38
39  return stack.isEmpty()40}```

leetcode

stack

greedy

## Next Post

LeetCode: Divide Two Integers

Feb 28, 2021

Search Posts