Widest Vertical Area Between Two Points Containing No Points - Problem

Imagine you're a city planner looking at a map with n buildings represented as points on a 2D plane, where each point points[i] = [xi, yi] has coordinates (x, y).

Your task is to find the widest vertical corridor between any two buildings such that no other buildings obstruct the path. Think of it as finding the widest north-south street you can build!

A vertical area is like an invisible corridor of fixed width that extends infinitely along the y-axis (infinite height). The widest vertical area is the one with maximum width between two x-coordinates.

Important: Buildings exactly on the edge of a corridor don't count as obstructions - they can be right next to the street!

Goal: Return the maximum width of any such vertical corridor.

Input & Output

example_1.py โ€” Basic Case
$ Input: points = [[8,7],[9,9],[7,4],[9,7]]
โ€บ Output: 1
๐Ÿ’ก Note: After sorting x-coordinates: [7,8,9,9]. The gaps are: 8-7=1, 9-8=1, 9-9=0. Maximum gap is 1.
example_2.py โ€” Larger Gap
$ Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]
โ€บ Output: 3
๐Ÿ’ก Note: After sorting x-coordinates: [1,1,3,5,8,9]. The gaps are: 1-1=0, 3-1=2, 5-3=2, 8-5=3, 9-8=1. Maximum gap is 3.
example_3.py โ€” Minimum Case
$ Input: points = [[1,1],[2,2]]
โ€บ Output: 1
๐Ÿ’ก Note: With only two points at x=1 and x=2, the only possible vertical area has width 2-1=1.

Visualization

Tap to expand
City Planning: Finding the Widest North-South Streetx=1x=3x=4x=5x=8x=9Widest StreetWidth = 3Sorted x-coordinates: [1, 3, 4, 5, 8, 9] โ†’ Gaps: [2, 1, 1, 3, 1] โ†’ Max Gap: 3
Understanding the Visualization
1
Ignore Building Heights
Y-coordinates don't matter for vertical streets - only east-west positions (x-coordinates) matter
2
Line Up Buildings
Sort all buildings by their east-west position from left to right
3
Measure Street Widths
Check the distance between each pair of adjacent buildings
4
Find Widest Street
The largest gap between adjacent buildings is your answer
Key Takeaway
๐ŸŽฏ Key Insight: Y-coordinates don't matter for vertical areas! Sort by x-coordinate and find the maximum gap between adjacent positions.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยณ)

For each of the nยฒ pairs of points, we check all n points to see if they lie between

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track maximum distance

n
2n
โœ“ Linear Space

Constraints

  • n == points.length
  • 2 โ‰ค n โ‰ค 105
  • points[i].length == 2
  • 0 โ‰ค xi, yi โ‰ค 109
Asked in
Amazon 15 Google 12 Microsoft 8 Apple 5
24.8K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen