Last Moment Before All Ants Fall Out of a Plank - Problem

Imagine a wooden plank of length n units with several ants walking on it. Each ant moves at exactly 1 unit per second - some moving left, others moving right.

Here's the interesting part: when two ants moving in opposite directions meet, they bounce off each other and reverse their directions instantly (no time lost). When an ant reaches either end of the plank, it falls off immediately.

Your Goal: Given the plank length n and the initial positions of ants moving left and right, determine when the very last ant falls off the plank.

Input: An integer n (plank length) and two arrays - left (positions of left-moving ants) and right (positions of right-moving ants).

Output: The time moment when all ants have fallen off the plank.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 4, left = [4,3], right = [0,1]
โ€บ Output: 4
๐Ÿ’ก Note: Left ant at pos 4 needs 4 seconds to reach pos 0. Left ant at pos 3 needs 3 seconds. Right ant at pos 0 needs 4 seconds to reach pos 4. Right ant at pos 1 needs 3 seconds. Maximum is 4 seconds.
example_2.py โ€” No Collisions
$ Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]
โ€บ Output: 7
๐Ÿ’ก Note: All ants move right. The rightmost ant at position 0 needs 7 seconds to reach the right end. This takes the longest time.
example_3.py โ€” Single Ant
$ Input: n = 7, left = [7], right = []
โ€บ Output: 7
๐Ÿ’ก Note: Only one ant moving left from position 7. It needs 7 seconds to reach position 0 and fall off.

Visualization

Tap to expand
0nโ†time = posโ†’time = n-posCollision PathDirect PathDirect Path๐Ÿ”‘ Key: Same travel distance either way!
Understanding the Visualization
1
Setup the Bridge
Place ants on a plank of length n with their initial directions
2
Collision Reality
Ants bounce off each other when they meet, creating complex paths
3
Mathematical Insight
Realize that collisions are equivalent to ants passing through each other
4
Simple Calculation
Each ant travels a fixed distance regardless of collisions
5
Find Maximum
The ant with the longest travel time determines the answer
Key Takeaway
๐ŸŽฏ Key Insight: Collisions don't change the total distance each ant must travel - they just create the illusion of complexity!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(M)

Single pass through all M ants to find maximum travel time

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables to track maximum time

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 104
  • 0 โ‰ค left.length โ‰ค n + 1
  • 0 โ‰ค right.length โ‰ค n + 1
  • 1 โ‰ค left[i] โ‰ค n
  • 0 โ‰ค right[i] โ‰ค n - 1
  • All values of left and right are unique
Asked in
Google 12 Amazon 8 Microsoft 6 Facebook 4
87.6K Views
Medium Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen