Validate Stack Sequences - Problem
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.
The arrays represent the order in which elements were pushed onto the stack and the order in which they were popped from the stack. Your task is to determine if the pop sequence is valid given the push sequence.
Key Points:
- Stack follows LIFO (Last In, First Out) principle
- All values in both arrays are distinct
- Both arrays have the same length
Input & Output
Example 1 — Valid Sequence
$
Input:
pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
›
Output:
true
💡 Note:
Push 1,2,3,4 → Pop 4 → Push 5 → Pop 5,3,2,1. This sequence is valid.
Example 2 — Invalid Sequence
$
Input:
pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
›
Output:
false
💡 Note:
After popping 4,3, we need to pop 5, but 5 hasn't been pushed yet when 3 was on top.
Example 3 — Simple Case
$
Input:
pushed = [1,2], popped = [2,1]
›
Output:
true
💡 Note:
Push 1,2 → Pop 2,1. Simple LIFO order works.
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
Understanding the Visualization
1
Input
Two arrays: pushed=[1,2,3,4,5], popped=[4,5,3,2,1]
2
Simulate
Use stack to mimic push/pop operations
3
Validate
Check if sequence is achievable
Key Takeaway
🎯 Key Insight: Use a stack to simulate the operations - if we can match the popped sequence exactly, it's valid
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code