Maximum Gap (LeetCode 164): Solution and Explanation

Medium
Array
Sorting
Bucket Sort
Radix Sort

Given an unsorted array, return the largest difference between two neighbours in its sorted order, using linear time and space. Fewer than two elements means the answer is 0.

Intuition

Sorting and scanning neighbours works, but it costs O(n log n). The question asks for linear time, so we need to learn about the sorted order without fully sorting.

Take the smallest value lo and the largest value hi. The n numbers split the span hi - lo into n - 1 gaps, and those gaps add up to hi - lo. So at least one gap is as wide as (hi - lo) / (n - 1). That is a lower bound on the answer.

Now cut the span into buckets narrower than that bound. Two numbers inside one bucket are closer than the bound, so they can never be the widest gap. The widest gap must jump from the largest value of one bucket to the smallest value of the next non-empty bucket. That means each bucket only has to remember its min and its max.

Approach: Pigeonhole buckets

  1. If there are fewer than two numbers, return 0. Find lo and hi; if they are equal, return 0.
  2. Set size = max(1, (hi - lo) // (n - 1)) and create (hi - lo) // size + 1 buckets.
  3. For each x, compute its bucket (x - lo) // size and update that bucket's min and max.
  4. Set prev = lo and walk the buckets in order, skipping empty ones.
  5. For each non-empty bucket, the candidate gap is its min minus prev. Keep the largest, then set prev to the bucket's max.
  6. Return the largest gap.

Step-by-step example

nums = [3,6,9,1]
  1. n = 4, lo = 1, hi = 9. The span 8 is split into 3 gaps, so size = 8 // 3 = 2.
  2. There are 8 // 2 + 1 = 5 buckets, covering [1,3), [3,5), [5,7), [7,9), [9,11).
  3. 3 goes into bucket 1, 6 into bucket 2, 9 into bucket 4 and 1 into bucket 0. Bucket 3 stays empty.
  4. Scan with prev = 1: bucket 1 gives 3 - 1 = 2, bucket 2 gives 6 - 3 = 3, bucket 3 is empty, bucket 4 gives 9 - 6 = 3.
  5. The largest candidate is 3, so the answer is 3.

Code: Python, Java, C++

1class Solution:
2    def maximumGap(self, nums: List[int]) -> int:
3        n = len(nums)
4        if n < 2:
5            return 0
6        lo, hi = min(nums), max(nums)
7        if lo == hi:
8            return 0
9        size = max(1, (hi - lo) // (n - 1))
10        count = (hi - lo) // size + 1
11        bucket_min = [math.inf] * count
12        bucket_max = [-math.inf] * count
13        for x in nums:
14            b = (x - lo) // size
15            bucket_min[b] = min(bucket_min[b], x)
16            bucket_max[b] = max(bucket_max[b], x)
17        best, prev = 0, lo
18        for b in range(count):
19            if bucket_min[b] == math.inf:
20                continue
21            best = max(best, bucket_min[b] - prev)
22            prev = bucket_max[b]
23        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass finds lo and hi, one pass fills the buckets, and one pass scans them. There are at most about n + 1 buckets.

Space

O(n)

Each bucket stores two numbers, and the number of buckets is linear in n.

Other approaches

Sort and scan (time O(n log n), space O(1) to O(n) depending on the sort)

Sort the array and take the largest difference between neighbours. Simple and often fast enough, but it does not meet the linear time requirement.

Radix sort and scan (time O(d * n), space O(n))

Sort with LSD radix sort on decimal or byte digits, which is linear for bounded integers, then scan neighbours. It meets the bound but is more code than the bucket trick.

Common mistakes

  • A bucket size of 0. When hi - lo is smaller than n - 1, integer division gives 0, so clamp the size to at least 1.
  • Forgetting the all-equal case. If lo equals hi there is nothing to divide, and the answer is 0.
  • Comparing a bucket's min with the previous bucket's max even when that previous bucket is empty. Carry prev forward from the last non-empty bucket instead.
  • Storing every value per bucket. Only the min and max matter, and keeping lists makes the code slower without changing the answer.

Frequently asked questions

Why can the widest gap never be inside one bucket?

Each bucket is at most size wide, and size is no larger than the average gap (hi - lo) / (n - 1). Two values in one bucket differ by less than size, while the widest gap is at least the average, so it must cross a bucket boundary.

Why is the number of buckets (hi - lo) // size + 1?

Bucket b covers values from lo + b * size up to lo + (b + 1) * size - 1. The largest value hi lands in bucket (hi - lo) // size, so that many plus one buckets cover every value.

Do I need to handle negative numbers?

Not for this problem, since values are between 0 and 10^9. The method still works with negatives because each bucket index is measured from lo.

Can the answer overflow a 32-bit integer?

No. Values are at most 10^9, so every difference fits in a signed 32-bit integer.