Three Stack Problems From the Coding Screen
Each of these is solved in one left-to-right pass with a stack that holds the elements still waiting for a decision.
asteroid_collision(asteroids)
- Each integer is an asteroid; its absolute value is the size and its sign the direction (positive moves right, negative moves left). All move at the same speed. When two collide the smaller explodes; equal sizes destroy both; two moving the same way, or moving apart, never meet. Return the list of asteroids that survive, in order.
is_balanced(s)
s contains only the characters ()[]{}. Return True if every opening bracket is closed by the matching type in the correct order.
longest_valid_parentheses(s)
s contains only ( and ). Return the length of the longest well-formed contiguous substring.
Hints
- A left-moving asteroid can only collide with right-moving asteroids already on the stack, and keeps colliding while it survives.
- For the longest valid substring, keep the index of the last unmatched
) at the bottom of the stack as a base and push indices of (.