#1637
Widest Vertical Area Between Two Points Containing No Points
EasyArraySortingSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the points based on their x-coordinates, we can easily find the maximum width between consecutive points, which is more efficient than checking all pairs.
⚙️
Algorithm
4 steps- 1Step 1: Sort the points based on their x-coordinates.
- 2Step 2: Initialize a variable to keep track of the maximum width.
- 3Step 3: Loop through the sorted points and calculate the width between consecutive points.
- 4Step 4: Update the maximum width if the current width is greater.
solution.py12 lines
1# Full working Python code
2points = [[8,7],[9,9],[7,4],[9,7]]
3
4def maxWidthOfVerticalArea(points):
5 points.sort(key=lambda x: x[0])
6 max_width = 0
7 for i in range(1, len(points)):
8 width = points[i][0] - points[i - 1][0]
9 max_width = max(max_width, width)
10 return max_width
11
12print(maxWidthOfVerticalArea(points))ℹ
Complexity note: The sorting step dominates the time complexity, making it O(n log n), while we only use a constant amount of extra space.
- 1Sorting the points allows us to efficiently find the maximum width between consecutive points.
- 2The y-coordinates are irrelevant for calculating vertical widths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.