FastPrepLast Moment Before All Ants Fall
Problems/Last Moment Before All Ants Fall

Last Moment Before All Ants Fall

AMD logoAMD● MediumINTERNONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report explicitly identifies LeetCode 1503. This independently authored statement uses its ant-collision core, with bounded inputs and an explicit no-ant case; approximate source match 95%. An exact source date is not available.

Ants move at one unit per second on a plank from 0 to n. Positions in left start moving left; positions in right start moving right. Whenever two ants meet, both reverse direction instantly. An ant falls when it reaches the endpoint it is moving toward, including at time zero. Return the time when the final ant falls, or 0 if there are no ants.

Function

lastMoment(n: int, left: int[], right: int[]) → int

Examples

Example 1

n = 4left = [4,3]right = [0,1]return = 4

Ignoring identities, the leftward exit times are 4 and 3 and the rightward times are 4 and 3. Their maximum is 4.

Example 2

n = 7left = []right = [1,3,5]return = 6

The three ants fall after 6, 4 and 2 seconds; the final time is 6.

Constraints

  • 1 <= n <= 1000000.
  • 0 <= left.length <= 1000.
  • 0 <= right.length <= 1000.
  • 0 <= left[i], right[i] <= 1000000.
  • Every starting position is between 0 and n inclusive, and no two ants start at the same position across either array.

More AMD problems

  • Insert After a Linked-List NodeONSITE INTERVIEW · Seen Oct 2026
  • LRU CacheONSITE INTERVIEW · Seen Oct 2026
  • Lowest Common Ancestor of a Binary TreePHONE SCREEN · Seen Oct 2026
All AMD interview questionsSee AMD hiring insights
Saved
public int lastMoment(int n, int[] left, int[] right) {
    // Write your code here.
}
Checking account…