Skip to main content

946. Validate Stack Sequences

https://leetcode.com/problems/validate-stack-sequences/

Python

from collections import deque


class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
remains = deque(popped)
stack = []

for num in pushed:
stack.append(num)
while stack and stack[-1] == remains[0]:
stack.pop()
remains.popleft()

return not remains

Rust

impl Solution {
pub fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
let mut stack = Vec::new();
let mut pop_index = 0;
for num in pushed {
stack.push(num);
while let Some(&top) = stack.last() {
if top == popped[pop_index] {
stack.pop();
pop_index += 1;
} else {
break;
}
}
}
pop_index == popped.len()
}
}

Go

func validateStackSequences(pushed []int, popped []int) bool {
stack := []int{}
popIndex := 0
for _, num := range pushed {
stack = append(stack, num)
for len(stack) > 0 && stack[len(stack)-1] == popped[popIndex] {
stack = stack[:len(stack)-1]
popIndex++
}
}
return popIndex == len(popped)
}