Leetcode #1503: Last Moment Before All Ants Fall Out of a Plank
In this guide, we solve Leetcode #1503 Last Moment Before All Ants Fall Out of a Plank in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Brainteaser, Array, Simulation
Intuition
The rules are explicit, so simulating the process step by step is safest.
Careful state updates prevent subtle bugs.
Approach
Translate the rules into state updates and apply them in order.
Track the final state or aggregate as required.
Steps:
- Translate rules into state updates.
- Iterate for each step.
- Return the final state.
Example
Input: n = 4, left = [4,3], right = [0,1]
Output: 4
Explanation: In the image above:
-The ant at index 0 is named A and going to the right.
-The ant at index 1 is named B and going to the right.
-The ant at index 3 is named C and going to the left.
-The ant at index 4 is named D and going to the left.
The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).
Python Solution
class Solution:
def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:
ans = 0
for x in left:
ans = max(ans, x)
for x in right:
ans = max(ans, n - x)
return ans
Complexity
The time complexity is , where is the length of the plank. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.