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
Visualization
Time & Space Complexity
Single pass through all M ants to find maximum travel time
Only using a few variables to track maximum time
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