Minimum Time Visiting All Points

Each pair-to-pair time is Chebyshev distance — max of |dx|, |dy|. Sum across the route.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
geometry math

Problem#

Visit each point in order. From any point you can move diagonally or orthogonally one unit per second. Return the minimum total time.

Examples#

  • [[1,1],[3,4],[-1,0]]7 (3 + 4).
  • [[3,2],[-2,2]]5.

Constraints#

  • 1 <= points.length <= 100.

Approach#

Between two points, the minimum time is the Chebyshev distance max(|dx|, |dy|) (you can chain diagonal moves until one coordinate matches, then go straight).

Solution#

Minimum Time Visiting All Points
class Solution {
public:
int minTimeToVisitAllPoints(vector<vector<int>>& points) {
int total = 0;
for (int i = 1; i < (int)points.size(); ++i) {
int dx = abs(points[i][0] - points[i-1][0]);
int dy = abs(points[i][1] - points[i-1][1]);
total += max(dx, dy);
}
return total;
}
};

Editorial#

With unit diagonal moves allowed (Chebyshev/king-move), the shortest path between two grid points is governed by the larger coordinate-delta. The total just sums these consecutive Chebyshev distances along the visiting order.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.