Widest Vertical Area Between Two Points Containing No Points (LeetCode 1637): Solution and Explanation

Easy
Array
Sorting

Find the widest vertical strip between two points that has no point strictly inside it.

Intuition

A vertical strip runs from the bottom of the plane to the top, so it contains a point whenever that point's x lies inside the strip. The y coordinate never matters.

Drop every point onto the x axis. An empty strip must sit between two x values with nothing in between, which means two values that are neighbors after sorting.

So the answer is just the largest gap between consecutive sorted x values.

Approach: Sort x and scan neighbor gaps

  1. Collect the x coordinate of every point.
  2. Sort the x values.
  3. For each i from 1 to n - 1, compute xs[i] - xs[i - 1] and keep the maximum.
  4. Return that maximum. Repeated x values give a gap of 0, which never wins unless every x is the same.

Step-by-step example

points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
  1. x values: 3, 9, 1, 1, 5, 8. Sorted: 1, 1, 3, 5, 8, 9.
  2. Gaps: 0, 2, 2, 3, 1.
  3. The largest gap is 3, between x = 5 and x = 8.
  4. Return 3.

Code: Python, Java, C++

1class Solution:
2    def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
3        xs = sorted(x for x, _ in points)
4        best = 0
5        for i in range(1, len(xs)):
6            best = max(best, xs[i] - xs[i - 1])
7        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Bucket sort (maximum gap trick) O(n)
Sort x and scan neighbor gaps O(n log n)
Time

O(n log n)

Sorting dominates; the gap scan is linear.

Space

O(n)

The sorted copy of the x values.

Other approaches

Bucket sort (maximum gap trick) (time O(n), space O(n))

Spread the x values into n buckets by range; the widest gap must cross buckets, so only bucket minimums and maximums matter. Linear time but more code.

Common mistakes

  • Sorting the points by y or by both coordinates and then using y in the gap. Only x matters.
  • Using the default JavaScript sort, which compares numbers as strings. Pass (a, b) => a - b.
  • Trying to deduplicate x values first. It is harmless but unnecessary, since equal neighbors give a gap of 0.

Frequently asked questions

Why can the widest strip only be between sorted neighbors?

If some x value lay strictly between the two edges, that point would be inside the strip. So the edges must be adjacent in sorted order.

Can the answer overflow a 32-bit int?

No. All x values are between 0 and 10^9, so any difference fits in a signed 32-bit integer.

What if all points share the same x?

Every gap is 0, so the answer is 0.