#1266
Minimum Time Visiting All Points
EasyArrayMathGeometryGreedy AlgorithmsDistance Calculation
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)
The optimal solution is actually the same as the brute force approach since the movement rules dictate that the fastest way to move between two points is to maximize diagonal movement first and then move straight. Thus, the same formula applies.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a variable to keep track of the total time.
- 2Step 2: Loop through each consecutive pair of points in the list.
- 3Step 3: For each pair, calculate the time taken to move from the first point to the second using the formula: max(abs(x2 - x1), abs(y2 - y1)).
- 4Step 4: Add the calculated time to the total time.
- 5Step 5: Return the total time after processing all points.
solution.py9 lines
1# Full working Python code
2
3def minTimeToVisitAllPoints(points):
4 total_time = 0
5 for i in range(len(points) - 1):
6 x1, y1 = points[i]
7 x2, y2 = points[i + 1]
8 total_time += max(abs(x2 - x1), abs(y2 - y1))
9 return total_timeℹ
Complexity note: The time complexity remains O(n) as we still iterate through the list of points once, and the space complexity is O(1) since we only use a fixed amount of extra space.
- 1The fastest way to move between two points is to maximize diagonal movement first.
- 2The distance formula used here is based on the Chebyshev distance, which is appropriate for this problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.