Last Moment Before All Ants Fall Out of a Plank
You have a wooden plank of length n units. Some ants are walking to the left, others to the right, all at speed 1. When two ants meet, they reverse direction. When an ant reaches either end of the plank, it falls off. Find the last moment before all ants have fallen off.
This is LeetCode 1503: Last Moment Before All Ants Fall Out of a Plank, and it is one of those problems where the hard part is not coding. The hard part is seeing the trick. Once you see it, the solution is three lines.
Why this problem matters
Simulation problems can feel overwhelming. You read the problem statement, think about tracking every ant and every collision, and the complexity spirals. But this problem is a masterclass in reframing. The right observation transforms it from a complicated simulation into a trivial calculation.
That skill, seeing through surface complexity to the underlying simplicity, is exactly what interviewers are testing. They want to know if you can step back and ask: "Does the collision actually change anything?"
The key insight: collisions do not matter
Two ants collide and reverse direction. That sounds important. But think about what actually happens. Ant A walks right, Ant B walks left, they meet at some point, and they both turn around.
Now imagine instead that they walk straight through each other. From a bird's-eye view, the set of positions occupied by ants at every moment in time is exactly the same. The only difference is which ant is at which position, and we do not care about individual identities. We only care about when the last ant falls off.
So collisions are irrelevant. Every ant walks in its initial direction until it falls off the plank. That means:
- An ant walking left from position
ptakespseconds to fall off the left edge (position 0). - An ant walking right from position
ptakesn - pseconds to fall off the right edge (positionn).
The answer is just the maximum of all those times.
This is one of the most famous "aha" moments in competitive programming. The insight that two identical objects colliding and reversing is the same as passing through each other comes up in physics puzzles too. Once you internalize it, you will recognize it instantly whenever a problem involves symmetric collisions.
The solution
def getLastMoment(n, left, right):
last = 0
for pos in left:
last = max(last, pos)
for pos in right:
last = max(last, n - pos)
return last
Let's walk through each part:
- Initialize
last = 0. This tracks the maximum time any ant takes to fall off. - For each ant walking left, its fall time is
pos(it has to walkposunits to reach position 0). Take the max. - For each ant walking right, its fall time is
n - pos(it has to walkn - posunits to reach positionn). Take the max. - Return the overall maximum.
That is the entire solution. No simulation, no collision tracking, no complex data structures.
You can also write it even more concisely:
def getLastMoment(n, left, right):
left_max = max(left) if left else 0
right_max = max(n - p for p in right) if right else 0
return max(left_max, right_max)
Both versions do the same thing. Pick whichever reads better to you.
Visual walkthrough
Let's trace through the insight step by step. The key is seeing that a collision with reversal produces the same positions as ants passing through each other.
Step 1: Two ants collide at position 3
Ant A walks right from 2, Ant B walks left from 4. They meet at position 3 after 1 second.
Step 2: After collision they reverse directions
A now walks left from 3, B now walks right from 3. They swapped directions.
Step 3: But that is identical to them passing through each other
If two identical ants pass through each other the outcome is the same. Only individual positions matter.
Step 4: So just compute the farthest distance for each ant
For left-walking ants the time is their position. For right-walking ants the time is n minus their position. The answer is the maximum.
With n = 7, left = [2, 5], and right = [0, 3, 6]:
- Left-walking ants: times are 2 and 5. Max is 5.
- Right-walking ants: times are 7, 4, and 1. Max is 7.
- Answer: max(5, 7) = 7.
The ant at position 0 walking right takes 7 seconds to fall off the right edge. That is the last one.
Complexity analysis
| Metric | Value |
|---|---|
| Time | O(n) where n is the total number of ants (length of left + length of right) |
| Space | O(1) extra space |
We scan each ant once and track a running maximum. No extra arrays or data structures needed.
The building blocks
This problem relies on two reusable patterns:
1. Running maximum
The core computation is finding the maximum value across a collection. You scan through the elements, keeping a running max variable updated at each step.
best = 0
for value in collection:
best = max(best, value)
This exact pattern appears in Best Time to Buy and Sell Stock (running min for profit), Maximum Subarray (running max for Kadane's), and dozens of other problems. The shape is always the same: accumulate an extremal value in a single pass.
2. Problem reframing through invariants
The real skill here is not the code. It is recognizing that the collision rule is a red herring. The positions of ants over time are invariant under the "pass through vs. reverse" interpretation. Once you identify that invariant, the problem collapses.
This kind of reframing shows up in many places. In problems involving cyclic rotations, you might realize the answer only depends on relative order. In problems involving swaps, you might realize the answer only depends on the final multiset. Always ask: "What actually changes, and what stays the same?"
Edge cases
Before submitting, make sure your solution handles these scenarios:
- Empty left or right list: one direction has no ants. Only consider the other direction. If both are empty, return 0.
- Ant at position 0 walking left: falls off immediately at time 0. Does not affect the answer unless all ants are at edges.
- Ant at position n walking right: falls off immediately at time 0. Same reasoning.
- All ants walking the same direction: no collisions at all, so the insight is trivially true. Just compute the max distance.
- Single ant: falls off in
posorn - posseconds. No collisions possible. - Two ants that would collide: the collision does not change the answer, confirming the core insight holds even in the simplest case.
From understanding to recall
The solution is three lines of code. You could memorize that in seconds. But the real challenge is recognizing when to apply the collision insight. In an interview, you will not see the problem title. You will see a description about ants, collisions, and a plank, and you need to quickly connect it to the "pass through each other" trick.
Spaced repetition helps here because it forces you to practice the recognition step, not just the coding step. You see the problem framing, recall the insight, and write the solution from scratch. After a few reps at increasing intervals, the pattern recognition becomes automatic.
The running max pattern is one of roughly 60 reusable building blocks that cover hundreds of LeetCode problems. Learning each one independently and drilling them with spaced repetition is far more effective than grinding random problems and hoping the insights stick.
Related posts
- Maximum Subarray - Another single-pass problem that uses a running max (Kadane's algorithm)
- Rotate Array - An array problem where the right observation makes the solution trivial
- Jump Game - Greedy reachability using a running farthest-reach variable
CodeBricks breaks this problem into its running-max and problem-reframing building blocks, then drills them independently with spaced repetition. You type each piece from scratch until the pattern is automatic. When an interview problem hides a simple answer behind surface complexity, you will see through it immediately.