algoadvance

Leetcode 1266. Minimum Time Visiting All Points

Problem Statement

You are given an array points where points[i] = [xi, yi] represents the coordinates of the i-th point on a 2D plane. You can move from point i to point i + 1 in exactly one of two ways:

  1. Move horizontally or vertically one unit.
  2. Move diagonally one unit.

Return the minimum time in seconds to visit all the points in the order given by points.

Clarifying Questions

  1. Q: Are the points guaranteed to be distinct? A: Yes, the problem does not mention overlapping points.

  2. Q: Can we move only in the 4 diagonal, horizontal, and vertical directions, or are there any restrictions? A: You can move only to the 8 directions allowed by the constraints - which are vertical, horizontal, and diagonal.

  3. Q: Are we required to visit the points in the exact order given? A: Yes, you need to follow the order provided in the input array.

Strategy

To determine the minimum time to visit all points, observe the following:

To minimize the moves to go from point A to point B:

Code

class Solution {
    public int minTimeToVisitAllPoints(int[][] points) {
        int total_time = 0;
        for (int i = 1; i < points.length; i++) {
            int x_diff = Math.abs(points[i][0] - points[i - 1][0]);
            int y_diff = Math.abs(points[i][1] - points[i - 1][1]);
            total_time += Math.max(x_diff, y_diff);
        }
        return total_time;
    }
}

Time Complexity

The solution involves a single loop iterating over the array of points, making it an O(N) time complexity, where N is the number of points in the input array. Each iteration involves constant time calculations (i.e., obtaining the absolute difference and their maximum), which do not affect the overall linear complexity.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI