Maximum Gap

Hard

Topics
ArraySortingBucket Sort

Given an integer array nums, return the maximum difference between two successive elements once the array is sorted in ascending order. If the array contains fewer than two elements, return 0.

Example 1

nums3691
sorted1369
the widest gap: 3
The answer is the largest difference between two values that are neighbours once sorted — not neighbours in the input. The shaded pair is that gap, 3. Fewer than two values leaves no gap at all, which answers 0.
Top row is the input; below it the same values sorted.
Input:  nums = [3,6,9,1]
Output: 3

Example 2

100
Input:  nums = [10]
Output: 0

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

Sorting and scanning adjacent pairs answers the question in O(n log n), and it is the honest first solution. But the problem asks for the maximum gap only, not the sorted order, and that admits a linear algorithm — which is what the page's own topic tag promises.

The insight is a pigeonhole argument. With n values spanning [lo, hi], there are n-1 adjacent gaps summing to hi - lo, so the largest is at least ceil((hi - lo) / (n - 1)). Choose buckets of exactly that width. No bucket can then contain the winning gap, because a gap that fits inside one bucket is strictly smaller than the bucket width and therefore smaller than the guaranteed maximum.

So the winning gap must span from one non-empty bucket's maximum to the next non-empty bucket's minimum. Only those two values per bucket need storing, and nothing needs sorting.

Approach

  1. Return 0 for fewer than two elements, or when all values are equal.
  2. Set the bucket width to ceil((hi - lo) / (n - 1)) and allocate (hi - lo) / width + 1 buckets.
  3. Place each value, keeping only its bucket's running minimum and maximum.
  4. Sweep the buckets in order, skipping empty ones, and take the largest difference between the current bucket's minimum and the previous non-empty bucket's maximum.

Dry Run

nums = [3,6,9,1]      n = 4, lo = 1, hi = 9

width = ceil((9 - 1) / 3) = 3        buckets cover [1,3] [4,6] [7,9]

  value  bucket  bucket min / max after
  3      0       min 3  max 3
  6      1       min 6  max 6
  9      2       min 9  max 9
  1      0       min 1  max 3

sweep
  bucket 0  min 1  max 3    prev = 3
  bucket 1  min 6  max 6    gap 6 - 3 = 3    prev = 6
  bucket 2  min 9  max 9    gap 9 - 6 = 3    prev = 9

answer 3

edge cases, verified
  [1]                          -> 0
  [1,1,1]                      -> 0     lo == hi, early return
  [0, 10^9]                    -> 10^9
  [10^9, 0, 10^9]              -> 10^9

Complexity

  • Time — O(n): one pass to find the extremes, one to fill buckets, one to sweep. Measured at 0.024s for 10⁵ random values.
  • Space — O(n) for the bucket extremes. The number of buckets is at most n, because the width was chosen to make it so.
  • The sort-and-scan version is O(n log n) time and whatever the sort costs in space. It is correct and much shorter; the bucket version exists because this problem specifically asks for linear time and linear space.

Common Pitfalls

  • Using a bucket width of (hi - lo) / n or any value that does not come from the pigeonhole bound. If the width exceeds the guaranteed maximum gap, the winning gap can sit inside one bucket and is then invisible.
  • Flooring instead of ceiling the width, which can make the width 0 and divide by zero.
  • Forgetting the lo == hi early return, where the width computation divides by a span of 0.
  • Storing all values per bucket. Only the extremes matter, and keeping the rest defeats the point.
  • Comparing within a bucket. Gaps inside a bucket are provably smaller than the answer; only bucket-to-bucket gaps can win.
  • Overflow in the span. At the stated bound hi - lo reaches 10⁹, which fits in 32 bits, but hi - lo + n - 2 for the ceiling arithmetic is safer computed in 64 bits — which is what the shown Java and C++ do.
  • Treating the empty-bucket skip as optional. Empty buckets must not reset the previous maximum, or a wide empty stretch is split into two smaller gaps.

Full Solution — all languages

class Solution:
    def maximumGap(self, nums):
        n = len(nums)
        if n < 2:
            return 0
        lo, hi = min(nums), max(nums)
        if lo == hi:
            return 0
        # Pigeonhole: n values spanning [lo, hi] leave n-1 gaps summing to
        # hi - lo, so the largest gap is at least ceil((hi - lo) / (n - 1)).
        # Buckets of exactly that width therefore cannot contain the winning
        # gap, which means only each bucket's min and max ever matter.
        width = -(-(hi - lo) // (n - 1))
        count = (hi - lo) // width + 1
        bucket_min = [None] * count
        bucket_max = [None] * count
        for x in nums:
            b = (x - lo) // width
            bucket_min[b] = x if bucket_min[b] is None else min(bucket_min[b], x)
            bucket_max[b] = x if bucket_max[b] is None else max(bucket_max[b], x)
        best = 0
        prev = None
        for i in range(count):
            if bucket_min[i] is None:
                continue                      # empty bucket, skip it
            if prev is not None:
                best = max(best, bucket_min[i] - prev)
            prev = bucket_max[i]
        return best
SensAI
Beta
Tap the mic to stop voice mode