algoadvance

1637. Widest Vertical Area Between Two Points Containing No Points

Given n points on a 2D plane where points[i] = [xi, yi], return the widest vertical area between two points such that no points are inside the area.

A vertical area is the area between two vertical lines.

The widest vertical area is the one with the maximum width.

Example 1:

Input: points = [[8,7],[9,9],[7,4],[9,7]]
Output: 1
Explanation: The vertical area between [8,7] and [9,9] is 1.

Example 2:

Input: points = [[3,1],[9,0],[1,0],[4,0],[7,0]]
Output: 3
Explanation: The vertical area between [1,0] and [4,0] is 3.

Constraints:

Clarifying Questions

  1. Do we need to consider the y-coordinates of the points in this problem?
    • No, the y-coordinates are irrelevant in finding the vertical area since we are only concerned with the x-coordinates for determining the width.
  2. Are duplicate points possible within the input?
    • Yes, duplicate points are possible, but they do not impact the logic for determining the widest vertical area.
  3. Will the list of points always contain at least two distinct x-coordinates?
    • Yes, according to the constraints, there will always be at least two points, and it is guaranteed that n >= 2.

Strategy

  1. Extract the x-coordinates from the list of points.
  2. Sort these x-coordinates.
  3. Compute the differences between consecutive x-coordinates to determine the widths of the vertical areas.
  4. Return the maximum value of these computed differences.

Code

Let’s implement this plan in Python:

def maxWidthOfVerticalArea(points):
    # Extract the x-coordinates and sort them
    x_coords = sorted(point[0] for point in points)
    
    # Compute the maximum difference between consecutive x-coordinates
    max_width = max(x_coords[i + 1] - x_coords[i] for i in range(len(x_coords) - 1))
    
    return max_width

# Example usage:
points1 = [[8,7],[9,9],[7,4],[9,7]]
points2 = [[3,1],[9,0],[1,0],[4,0],[7,0]]
print(maxWidthOfVerticalArea(points1))  # Output: 1
print(maxWidthOfVerticalArea(points2))  # Output: 3

Time Complexity

Thus, the overall time complexity is (O(n \log n)).

Try our interview co-pilot at AlgoAdvance.com