#1503
Last Moment Before All Ants Fall Out of a Plank
MediumArrayBrainteaserSimulationArraySimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of simulating each ant's movement, we can directly calculate the time it takes for each ant to fall off the plank based on their direction. This avoids unnecessary calculations and gives us the result in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a variable to keep track of the maximum time.
- 2Step 2: For each ant in the 'left' array, compute the time to fall off the plank (which is simply their position).
- 3Step 3: For each ant in the 'right' array, compute the time to fall off the plank (which is n - their position).
- 4Step 4: Return the maximum of these computed times.
solution.py2 lines
1def getLastMoment(n, left, right):
2 return max(max(left, default=0), n - min(right, default=n))ℹ
Complexity note: This solution runs in O(n) time as we only need to find the maximum and minimum values from the two arrays, which is efficient.
- 1When ants meet and change directions, it can be treated as if they continue moving in their original direction.
- 2The last moment an ant falls off is determined by the furthest distance any ant has to travel to the edge.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.