Problem 1503

Abstract / Summary

Find the latest time before all ants leave a plank given their starting positions and constant speed.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1503.py

class Solution:
    def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:
        # if two ants meet then basically nothing changes:
        # ant A and B change direction but A moves the same path that B would move
        # if there were no A
        # more or less A becomes B and B becomes A
        # so the total duration of ant X on the plank is its distance to the end
        # of the direction it's walking
        l = max(left)      if left  else 0
        r = n - min(right) if right else 0
        return max(l, r)
11 lines | 560 bytes | submitted November 3, 2023 | GitHub   120% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 68% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “last moment an ant falls off a plank” problem. It receives the length of the plank (n) and two collections of integer positions: left for ants initially moving toward the left end and right for ants initially moving toward the right end. The method returns the latest time at which any ant leaves the plank.

Core Logic

The algorithm relies on the observation that when two ants collide they simply exchange identities; the physical outcome is indistinguishable from the ants passing through each other. Consequently, each ant’s travel time equals the distance from its starting point to the end of the plank in the direction it is heading. The overall answer is the maximum of those individual travel times.

Determining the farthest left-moving ant

l = max(left) if left else 0

For an ant moving left, the time to fall off equals its current coordinate because the left end is at position 0. The expression extracts the greatest coordinate among all left-moving ants, which yields the longest such travel time. If the left list is empty, the fallback value 0 correctly indicates that no left-moving ant contributes to the answer.

Determining the farthest right-moving ant

r = n - min(right) if right else 0

A right-moving ant reaches the right end at coordinate n. Its travel time is the difference between n and its starting position. The smallest starting coordinate among right-moving ants produces the longest distance to the right end, because the farther left an ant starts, the longer it must travel. When right is empty, the fallback 0 reflects the absence of right-moving ants.

Selecting the overall last moment

return max(l, r)

The final result is the larger of the two computed durations, representing the latest moment any ant leaves the plank.

Edge Cases Handled

When both left and right are empty, the method returns 0, which correctly indicates that no ant is present to fall off.

If only one of the lists is empty, the corresponding fallback (0) ensures that the non-empty side solely determines the answer.

The code also works when ants start at the extreme ends of the plank (position 0 or n). In those cases the distance calculation yields 0 for that ant, and the maximum operation naturally ignores it if another ant takes longer.

The implementation tolerates a plank length of zero (n == 0). Both distance calculations reduce to 0, and the method returns 0, matching the expectation that no time elapses before the (non-existent) ants fall off.

Performance Optimizations

The solution leverages Python’s built-in max and min functions, which are implemented in C and run in linear time over the input sequences. By calling each function once, the algorithm scans each list a single time, achieving the minimal possible number of passes.

Memory usage is constant: only three integer variables (l, r, and the return value) are allocated regardless of the size of the input lists. No auxiliary data structures are created, and the original input lists remain untouched.

Because the computation consists solely of arithmetic on integer values, the runtime overhead is negligible even for large inputs, and the function scales gracefully with the number of ants.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long wooden plank with many tiny ants crawling on it. Some ants are walking toward the left side, and some are walking toward the right side. When two ants bump into each other, they simply turn around and head the other way. This is just like them walking right through each other because they all move at the exact same speed.

Because the ants act like they pass through each other, the ant that takes the longest to fall off the plank is the one that has the farthest to walk. The ants walking to the left just need to reach the very start of the plank, and the ants walking to the right just need to reach the very end of the plank.

This code goes through all the ants walking to the left and finds the one that is the farthest away from the start. Then it looks at all the ants walking to the right and finds the one that is the farthest away from the end. By looking at these two distances, the code figures out which ant will be the very last one remaining on the plank.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 9 | μ = 8.46 | σ = 0.93

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
FelixFan1122 C#
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
FelixFan1122 C#
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
24 links | 15 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

13 solutions   November 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality