Monotonic stack Flashcards

(8 cards)

1
Q

What is the definition of a Monotonic Stack?

A

Maintains stack in increasing/decreasing order for comparisons.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When is a Monotonic Stack used?

A

Next/previous greater/smaller elements.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the key steps in using a Monotonic Stack?

A
  1. Initialize empty stack.
  2. Pop stack while top violates monotonicity.
  3. Push current element, update result.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How does a Monotonic Stack apply to Asteroid Collision?

A

Simulate asteroid collisions using stack to track asteroids, pop if collision destroys smaller.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the complexity of a Monotonic Stack?

A

Time: O(n), Space: O(n).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are some gotchas when using a Monotonic Stack?

A

Empty stack, same-size collisions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Provide a code example for a Monotonic Stack.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a visual representation for a Monotonic Stack?

A

[Add image manually].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly