Validate Stack Sequences
Master this topic with zero to advance depth.
Validate Stack Sequences
Determine if a sequence of indices popped could have resulted from a sequence of pushed operations on an empty stack.
Visual Representation
pushed = [1, 2, 3], popped = [2, 3, 1]
1. Push 1: Stack [1]
2. Push 2: Stack [1, 2]. Top 2 == popped[0]. Pop. Stack [1]
3. Push 3: Stack [1, 3]. Top 3 == popped[1]. Pop. Stack [1]
4. No more pushes. Top 1 == popped[2]. Pop. Stack []
Result: TrueExamples
Level I: Brute Force (Try All Push/Pop Orders)
Intuition
Without insight, we could try all possible sequences of push/pop operations on pushed[] to check if any of them matches popped[]. However, given that each element must be pushed exactly once, the simulation approach is actually already optimal in practice. The 'brute force' here is to consider a naive simulation without the greedy insight.
Level III: Optimal (Greedy Simulation)
Intuition
Iterate through the pushed array and push each element onto a stack. After each push, greedily pop elements from the stack as long as the stack top matches the current element in the popped array.
Detailed Dry Run
| Push | Stack | Popped Pointer | Action |
|---|---|---|---|
| 1 | [1] | 0 | Push |
| 2 | [1, 2] | 0 | Push |
| - | [1] | 1 (2 matched) | Pop |
| 3 | [1, 3] | 1 | Push |
| - | [] | 3 (3 then 1 matched) | Pop, Pop |
⚠️ Common Pitfalls & Tips
All elements in pushed and popped are distinct as per standard constraints. Ensure you pop as many matching elements as possible after each push.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.