1266 Minimum Time Visiting All Points

Published:

Problem

Solution

Intuition

The problem is quite simple and requires us to find the minimum amount of time needed to traverse the points in the given order. This requires a simple math trick to easily calculate as we can move vertically, horizontally, and diagonally.

Approach

For each point, calculate the maximum of the absolute vertical and horizontal difference between the previous point’s coordinates and add that to the result.

Complexity

  • Time complexity: $O(n)$. We iterate through the points once doing a constant time operation during each iteration.

  • Space complexity: $O(1)$. We do not use any additional space.

Code

class Solution:
    def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
        res = 0

        for i in range(1, len(points)):
            res += max(abs(points[i][0] - points[i-1][0]), abs(points[i][1] - points[i-1][1]))
        return res