Last Moment Before All Ants Fall Out of a Plank - Problem
We have a wooden plank of length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some ants move to the left, others move to the right.
When two ants moving in different directions meet at some point, they change directions and continue moving. Assume changing directions takes no additional time.
When an ant reaches one end of the plank at time t, it falls out of the plank immediately.
Given an integer n and two integer arrays left and right, representing the positions of ants moving left and right respectively, return the moment when the last ant(s) fall out of the plank.
Input & Output
Example 1 — Basic Case
$
Input:
n = 4, left = [4,3], right = [0,1]
›
Output:
4
💡 Note:
Ant at position 4 moving left takes 4 seconds to reach position 0. Ant at position 3 moving left takes 3 seconds. Ant at position 0 moving right takes 4 seconds to reach position 4. Ant at position 1 moving right takes 3 seconds. Maximum time is 4.
Example 2 — Only Left Moving
$
Input:
n = 7, left = [0,1,2,3,4,5,6,7], right = []
›
Output:
7
💡 Note:
All ants move left. The ant at position 7 takes the longest time (7 seconds) to reach the left edge at position 0.
Example 3 — Single Ant
$
Input:
n = 7, left = [], right = [5]
›
Output:
2
💡 Note:
Single ant at position 5 moving right takes 7-5=2 seconds to reach the right edge at position 7.
Constraints
- 1 ≤ n ≤ 104
- 0 ≤ left.length ≤ n + 1
- 0 ≤ right.length ≤ n + 1
- 1 ≤ left[i] ≤ n
- 0 ≤ right[i] ≤ n - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Plank of length n with ants at specific positions moving left or right
2
Process
Ants move at speed 1 unit/second, change directions when they collide
3
Output
Time when the last ant falls off either edge
Key Takeaway
🎯 Key Insight: Collisions don't change the total time - just calculate max distance to nearest edge
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code