Python 1637.py
class Solution:
def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
have = sorted(set([ x for x,y in points ]))
result = 0
for i in range(1, len(have)):
gap = have[i] - have[i - 1]
result = max(result, gap)
return result
Difficulty
and has an acceptance rate of about 87% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the maximum width of a vertical strip that contains no points from a given set of 2-D coordinates. The algorithm extracts all distinct x-coordinates, sorts them, and then scans the sorted list to find the largest difference between consecutive x values. The final result is the greatest horizontal gap, which corresponds to the maximum possible width of a vertical area without any points inside it.
Extraction and Deduplication of X-Coordinates
The first logical block isolates the x component from each point and removes duplicates.
have = sorted(set([ x for x, y in points ]))
- The list comprehension iterates over the input list
points, pulling out the first element of each pair. seteliminates repeated x values, guaranteeing that each coordinate is considered only once.sortedorders the unique x values in ascending order, which is essential for the subsequent gap calculation.
Edge Cases Handled
When the input contains multiple points sharing the same x-coordinate, the deduplication step ensures that those points do not artificially inflate the number of gaps. If all points lie on a single vertical line, the set will contain exactly one element; the later loop will not execute, and the function will correctly return 0 because there is no space between distinct x positions.
Iterative Gap Computation
The core of the solution iterates through the sorted x values, computes the distance between each pair of neighbours, and tracks the maximum distance encountered.
result = 0
for i in range(1, len(have)):
gap = have[i] - have[i - 1]
result = max(result, gap)
- The loop starts at index
1so that each iteration has a valid predecessor ati-1. gaprepresents the width of the vertical strip between two adjacent x-coordinates.resultis updated only when a larger gap is found, preserving the maximum value seen so far.
Edge Cases Handled
If the list have contains fewer than two elements, the range produces no iterations, leaving result at its initial value 0. This correctly reflects that no vertical area can be formed when there is only one distinct x-coordinate.
When points are spaced uniformly, each computed gap will be identical, and the algorithm will still return that common distance as the maximum width.
Return Value
After processing all gaps, the function returns the stored maximum.
return result
The returned integer directly represents the widest vertical region that contains no points from the original set.
Performance Optimizations
The solution leverages built-in data structures that are highly optimized in the Python runtime.
- Converting the list of x-coordinates to a
setprovides O(1) average-time membership checks and eliminates duplicates in a single pass. - Sorting the unique values with
sorteduses Timsort, which is adaptive and runs in linear time on already-sorted or partially-sorted data, offering a practical speed advantage for inputs that exhibit such patterns. - The subsequent linear scan over the sorted list performs only constant-time arithmetic and comparison per element, ensuring that the overall work after sorting is minimal.
By separating deduplication, sorting, and scanning into distinct phases, the code avoids unnecessary repeated work and keeps memory usage proportional to the number of distinct x-coordinates.
Overall, the implementation delivers an efficient solution that scales well with the size of the input while correctly handling all edge conditions inherent to the problem definition.
ELI5 - Simplified Explanation
Imagine you have a big piece of paper with many stickers on it. Each sticker is at a special spot defined by two numbers. One number tells you how far across the paper the sticker is, and the other number tells you how high up it is.
The goal here is to find the largest empty hallway that runs from the top of the paper to the bottom without hitting any stickers.
First, the code collects all the side-to-side numbers from the stickers and puts them in a row from smallest to largest, just like lining up toys by their size. It also ignores any stickers that share the exact same side-to-side spot because they wouldn't create a gap.
Next, the code walks down this line of numbers one by one. At each stop, it looks at the gap between the current sticker and the one that came just before it. It remembers which gap is currently the biggest one it has found so far. By the time it finishes looking at all the gaps, the biggest one is the answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | JS | Java | Go | TS | |||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | C | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | C | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 164: Maximum Gap
- problem 2274: Maximum Consecutive Floors Without Special Floors
Solved On The Same Day
- problem 1550: Three Consecutive Odds
- problem 1629: Slowest Key
- problem 1684: Count the Number of Consistent Strings
- problem 1630: Arithmetic Subarrays
- problem 1663: Smallest String With A Given Numeric Value
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality