We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Minimum Time Visiting All Points

Number: 1395

Difficulty: Easy

Paid? No

Companies: Google, Media.net


Problem Description

Given a series of points in the 2D plane, determine the minimum time (in seconds) required to visit all points in the given order. You can move vertically, horizontally, or diagonally (which covers one unit in both x and y direction in one second). The optimal move between any two points is to move diagonally as much as possible then vertically or horizontally if needed.


Key Insights

  • The optimal movement between two points is governed by the maximum of the horizontal and vertical distances.
  • Diagonal moves allow simultaneous reduction in both x and y distances.
  • For any two points, the minimum number of moves is max(|dx|, |dy|).

Space and Time Complexity

Time Complexity: O(n), where n is the number of points because we iterate through the list once. Space Complexity: O(1), as we only use constant extra space for computation.


Solution

The idea is to iterate through the array of points and for each consecutive pair calculate the difference in x (dx) and y (dy). The minimum time to travel from one point to another is given by the maximum of the absolute values of dx and dy. This is because moving diagonally reduces both differences simultaneously, and after using as many diagonal moves as possible, the remaining difference equals the excess of one over the other. Summing these values for each pair gives the final result.

Data structures:

  • Array: to hold the list of points.

Algorithm:

  1. Initialize a variable to hold total time.
  2. Iterate through the list of points.
  3. For each pair, compute dx, dy.
  4. Add max(|dx|, |dy|) to the total time.
  5. Return the total time.

Code Solutions

# Python solution for Minimum Time Visiting All Points
def min_time_to_visit_all_points(points):
    # Initialize the total time counter.
    total_time = 0
    
    # Iterate over the points except the last one, comparing with its subsequent point.
    for i in range(len(points) - 1):
        # Calculate absolute differences for x and y coordinates.
        dx = abs(points[i+1][0] - points[i][0])
        dy = abs(points[i+1][1] - points[i][1])
        # The required time is the maximum of these differences.
        total_time += max(dx, dy)
    
    return total_time

# Example usage:
points = [[1,1],[3,4],[-1,0]]
print(min_time_to_visit_all_points(points))  # Expected output: 7
← Back to All Questions