Problem 1637

Abstract / Summary

Find the widest gap between vertical columns that do not contain any points.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
9 lines | 305 bytes | submitted November 14, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 87% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.
  • set eliminates repeated x values, guaranteeing that each coordinate is considered only once.
  • sorted orders 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 1 so that each iteration has a valid predecessor at i-1.
  • gap represents the width of the vertical strip between two adjacent x-coordinates.
  • result is 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 set provides O(1) average-time membership checks and eliminates duplicates in a single pass.
  • Sorting the unique values with sorted uses 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.56 | σ = 1.26

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 16 authors | 8 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

3 easy 2 medium
6 solutions   November 14, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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