Leetcode 1266. Minimum Time Visiting All Points
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:
Return the minimum time in seconds to visit all the points in the order given by points
.
Q: Are the points guaranteed to be distinct? A: Yes, the problem does not mention overlapping points.
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.
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.
To determine the minimum time to visit all points, observe the following:
To minimize the moves to go from point A
to point B
:
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;
}
}
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.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?