#946
Validate Stack Sequences
MediumArrayStackSimulationStackSimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use a stack to simulate the push and pop operations efficiently. By maintaining a pointer for the popped array, we can determine if the sequence is valid in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty stack and a pointer for the popped array.
- 2Step 2: Iterate through each element in the pushed array, pushing elements onto the stack.
- 3Step 3: After each push, check if the top of the stack matches the current element in the popped array. If it does, pop it and move the pointer in the popped array.
- 4Step 4: At the end, check if all elements have been popped.
solution.py9 lines
1def validateStackSequences(pushed, popped):
2 stack = []
3 j = 0
4 for x in pushed:
5 stack.append(x)
6 while stack and stack[-1] == popped[j]:
7 stack.pop()
8 j += 1
9 return j == len(popped)ℹ
Complexity note: The time complexity is O(n) because we traverse each element in the pushed array once, and the space complexity is O(n) due to the stack storing elements.
- 1The order of popping must always respect the last-in-first-out (LIFO) nature of the stack.
- 2The pushed and popped arrays must contain the same elements in different orders.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.