Skip to main content
Back to problems
#946
Medium Algorithms

Validate stack sequences

Array Stack Simulation
70.2% acceptance
Feb 25, 2026
6099
130
Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn validate_stack_sequences(pushed: Vec<i32>, popped: Vec<i32>) -> bool {
    let mut stack: Vec<i32> = Vec::new();
    let mut pop_idx = 0;
    for &x in &pushed {
      stack.push(x);
      while !stack.is_empty() && stack.last() == Some(&popped[pop_idx]) {
        stack.pop();
        pop_idx += 1;
      }
    }
    stack.is_empty()
  }
}