Validate Stack Sequences - Problem

Imagine you're watching someone use a stack data structure, but you can only see the push and pop sequences they performed. Given two integer arrays pushed and popped, each containing distinct values, your task is to determine if these sequences could represent valid stack operations on an initially empty stack.

The pushed array shows the order in which elements were pushed onto the stack, while popped shows the order in which elements were popped from the stack. Remember that a stack follows LIFO (Last In, First Out) principle - you can only pop the most recently pushed element that hasn't been popped yet.

Goal: Return true if the given sequences are valid, false otherwise.

Example: If pushed = [1,2,3,4,5] and popped = [4,5,3,2,1], this is valid because we could: push 1,2,3,4 → pop 4 → push 5 → pop 5 → pop 3 → pop 2 → pop 1

Input & Output

example_1.py — Valid Stack Sequence
$ Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
💡 Note: We can achieve this sequence: push 1,2,3,4 → pop 4 → push 5 → pop 5 → pop 3 → pop 2 → pop 1. The stack operations follow LIFO order correctly.
example_2.py — Invalid Stack Sequence
$ Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
💡 Note: After popping 4 and 3, element 5 hasn't been pushed yet when we try to pop it. The sequence violates stack LIFO constraints.
example_3.py — Single Element
$ Input: pushed = [1], popped = [1]
Output: true
💡 Note: Simple case: push 1, then pop 1. This is obviously valid.

Constraints

  • 1 ≤ pushed.length ≤ 1000
  • 0 ≤ pushed[i] ≤ 1000
  • All elements in pushed are unique
  • popped.length == pushed.length
  • popped is a permutation of pushed

Visualization

Tap to expand
🍽️ Restaurant Plate Stack ValidationPlate StackPlate 4Plate 3Plate 2Plate 1Service Order: [4, 5, 3, 2, 1]✓ Can serve plate 4 (top of stack)Add Plate 5, Then ServePush plate 5, immediately serve itContinue LIFO ServiceServe plates 3, 2, 1 from top downServe!💡 Key Insight: Greedy Strategy Works!If we can serve a plate (stack top matches request), we must serve it immediately.
Understanding the Visualization
1
Stack Clean Plates
Kitchen staff stack plates 1,2,3,4 in order
2
Serve Customer
Customer needs plate 4 (top plate) - serve immediately
3
Add More Plates
Stack plate 5, then serve it when requested
4
Continue Service
Serve remaining plates 3,2,1 from top of stack
5
Validation Complete
All plates served in correct LIFO order - sequence valid!
Key Takeaway
🎯 Key Insight: The greedy simulation approach works because stack operations are deterministic - when the top element matches our target, we must pop it immediately rather than waiting.
Asked in
Amazon 15 Microsoft 12 Google 8 Meta 6
126.8K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen