946. Validate Stack Sequences - Explanation
Description
Start with an empty stack. Push all values in pushed in the given order, and pop all values in the order specified by popped. Pushes and pops may be interleaved. Return true if such an operation sequence exists, or false otherwise. All pushed values are distinct, and popped is a permutation of them. A pop removes the most recently pushed value that remains on the stack.
Example 1:
Input: pushed = [1,2,3]
popped = [2,1,3]
Output: trueExplanation: Push 1 and 2, pop 2 and 1, then push and pop 3. The pop order is exactly [2,1,3].
Example 2:
Input: pushed = [1,2,3]
popped = [3,1,2]
Output: falseExplanation: To pop 3 first, all three values must be pushed. Then 2 is on top of 1, so 1 cannot be popped next.
Example 3:
Input: pushed = [0]
popped = [0]
Output: trueExplanation: Push 0 and then pop it. This produces the requested single-value pop sequence.
Constraints:
1 <= pushed.length <= 1000pushed.length == popped.length0 <= pushed[i] <= 1000- All values in
pushedare distinct. poppedis a permutation ofpushed.
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Stack Data Structure - Understanding push and pop operations and LIFO (Last-In-First-Out) behavior
- Simulation - Mimicking a process step-by-step to verify if a sequence of operations is valid
- Two Pointers - Using indices to track positions in multiple arrays simultaneously
1. Stack
Intuition
We can simulate the actual push and pop operations on a stack to verify if the sequences are valid. The key insight is that whenever we push an element, we should immediately try to pop as many elements as possible that match the expected pop sequence. If the simulation completes with an empty stack, the sequences are valid.
Algorithm
- Initialize an empty stack and a pointer
ito track position in thepoppedarray. - Iterate through each element in the
pushedarray and push it onto the stack. - After each push, check if the stack top matches the current element in
popped(at indexi). - While there is a match, pop from the stack and increment the pointer
i. - Continue until no more matches are found or the stack is empty.
- After processing all elements, return
trueif the stack is empty, indicating all elements were successfully popped in the correct order.
Time & Space Complexity
- Time complexity:
- Space complexity:
2. Two Pointers
Intuition
Instead of using a separate stack, we can reuse the pushed array itself as the stack. The left portion of the array acts as our stack, eliminating the need for extra space. This works because as we process elements, we overwrite positions that are no longer needed.
Algorithm
- Use two pointers:
lrepresents the top of our simulated stack withinpushed, andrtracks position inpopped. - Iterate through each element in
pushedand write it to positionl, then incrementl. - After each write, check if the element at position
l-1matchespopped[r]. - While there is a match and
l > 0, incrementrand decrementlto simulate popping. - Continue processing all elements in
pushed. - Return
trueiflequals0, meaning all elements were successfully matched and popped.
Time & Space Complexity
- Time complexity:
- Space complexity: extra space.
Common Pitfalls
Popping Without Checking Stack Emptiness
When simulating stack operations, always verify the stack is non-empty before attempting to pop or access the top element. Failing to check this condition can lead to runtime errors or incorrect comparisons with an empty stack.
Not Popping Greedily After Each Push
The key insight is that after each push, you should immediately pop as many elements as possible that match the expected pop sequence. Delaying pops or only checking once at the end will lead to incorrect results because the order of operations matters in stack simulations.
Forgetting to Verify Complete Stack Emptiness
After processing all pushed elements, the stack must be completely empty for the sequences to be valid. If elements remain in the stack, it means not all pops could be matched, indicating an invalid sequence. Always check that the final stack size is zero.
Sign in to join the discussion