Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A diagonal move reduces both coordinate differences simultaneously. Use diagonal moves until the smaller difference is exhausted, then finish along the remaining axis. The required time is therefore max(abs(dx), abs(dy)), and no route can be faster because one coordinate must change by that larger amount.
Approach
For each consecutive pair of required points, compute the absolute horizontal and vertical differences. Add the smaller difference for diagonal travel and the leftover difference for straight travel, exactly as the reference branches do. Sum these pairwise minimum times because the points must be visited in order. A repeated point contributes zero, and a one-point input requires no movement.
class Solution:
def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
n = len(points)
res = 0
for i in range(1, n):
dx = abs(points[i][0] - points[i - 1][0])
dy = abs(points[i][1] - points[i - 1][1])
if dx < dy:
res += dx + (dy - dx)
elif dy < dx:
res += dy + (dx - dy)
else:
res += dx
return resComplexity analysis
For n points, the code computes the Chebyshev distance for each adjacent pair, taking O(n) time and O(1) auxiliary space.
