Skip to main content
Back to problems
#1503
Medium Algorithms

Last moment before all ants fall out of a plank

Array Brainteaser Simulation
68.2% acceptance
Feb 25, 2026
1577
439
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. Some of the ants move to the left, the other move to the right. When two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches one end of the plank at a time t, it falls out of the plank immediately. Given an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn get_last_moment(n: i32, left: Vec<i32>, right: Vec<i32>) -> i32 {
    let max_left = left.iter().copied().max().unwrap_or(0);
    let max_right = right.iter().map(|&x| n - x).max().unwrap_or(0);
    max_left.max(max_right)
  }
}