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
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