Minimum Time Visiting All Points

To solve this problem, we need to understand that we can move diagonally, which means we can move both in the x and y directions simultaneously. When moving from one point to another, the time it takes is the maximum of the absolute difference in the x coordinates and the absolute difference in the y coordinates. This is because we can move diagonally until we reach the line y=x (or y=-x), then move vertically or horizontally to the target point. The time is the maximum of the differences because we have to cover the farthest distance, either horizontally or vertically.

1
2
3
4
5
6
7
8
class Solution:
    def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
        time = 0
        for i in range(len(points) - 1):
            dx = abs(points[i+1][0] - points[i][0])
            dy = abs(points[i+1][1] - points[i][1])
            time += max(dx, dy)
        return time

In this code, we’re iterating over the list of points. For each point, we’re calculating the absolute difference in the x and y coordinates with the next point. We then add the maximum of these differences to the total time. After going through all the points, we return the total time.

This solution has a time complexity of O(n), where n is the number of points, because we’re going through the list of points once. It has a space complexity of O(1), because we’re not using any additional data structures that scale with the input size.