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
1function Stack() {2 const stack = []34 this.push = function (el) {5 stack.push(el)6 }78 this.pop = function () {9 return stack.pop()10 }1112 this.peek = function () {13 return stack[stack.length - 1]14 }1516 this.isEmpty = function () {17 return stack.length === 018 }19}2021/**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 }3839 return stack.isEmpty()40}
Comments
Loading comments...
Tags
leetcode
stack
greedy
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.