Monotonic stack Flashcards
(8 cards)
What is the definition of a Monotonic Stack?
Maintains stack in increasing/decreasing order for comparisons.
When is a Monotonic Stack used?
Next/previous greater/smaller elements.
What are the key steps in using a Monotonic Stack?
- Initialize empty stack.
- Pop stack while top violates monotonicity.
- Push current element, update result.
How does a Monotonic Stack apply to Asteroid Collision?
Simulate asteroid collisions using stack to track asteroids, pop if collision destroys smaller.
What is the complexity of a Monotonic Stack?
Time: O(n), Space: O(n).
What are some gotchas when using a Monotonic Stack?
Empty stack, same-size collisions.
Provide a code example for a Monotonic Stack.
```python
from typing import List
def asteroid_collision(asteroids: List[int]) -> List[int]:
stack: List[int] = []
for asteroid in asteroids:
while True:
if not stack or asteroid > 0 or stack[-1] < 0:
stack.append(asteroid)
break
if stack[-1] == -asteroid:
stack.pop()
break
if stack[-1] > -asteroid:
break
stack.pop()
return stack
~~~
What is a visual representation for a Monotonic Stack?
[Add image manually].