Maximum Gap

MediumBucket Sort · Pigeonhole🧩 Bucket & Counting SortLeetCode #164 ↗Updated

Problem

Given an array nums of non-negative integers, imagine it sorted and return the largest difference between two neighbours in that sorted order. If the array has fewer than two elements, return 0. The intended solution runs in linear time and linear extra space.
Input[3,6,9,1]Output3 (sorted 1,3,6,9)
Input[10]Output0
Input[1,10000000]Output9999999

1 ≤ n ≤ 105  ·  0 ≤ nums[i] ≤ 109  ·  O(n) time and space required

Try it yourself

Java
class Solution {
    public int maximumGap(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
With n numbers spread over [lo, hi], the biggest gap is at least (hi - lo) / (n - 1). Use buckets narrower than that: no answer can live inside one bucket, so you only need each bucket's min and max.
PatternBucket & Counting Sort

Instinct Keys live in a small, known range (letters, frequencies 1..n, bounded values) - index an array by the key instead of comparing, and get O(n).

Memory hack Don't compare, just file it - every value walks straight to its own pigeonhole, then you read the shelves in order.

Open the Bucket & Counting Sort guide →

Approaches

Brute ForceSort, then Scan Neighbours

Time O(n log n)Space O(log n)

Sort a copy and compare each element with the one before it, keeping the largest difference. Sorting puts every candidate pair side by side, so a single scan finds the answer.

Java
public int maximumGap(int[] nums) {
    if (nums.length < 2) return 0;
    int[] a = nums.clone();
    Arrays.sort(a);
    int best = 0;
    for (int i = 1; i < a.length; i++) best = Math.max(best, a[i] - a[i - 1]);
    return best;
}

Three lines and obviously right, but comparison sorting misses the linear bound.

At a glance

LevelApproachTimeSpace
Brute ForceSort, then Scan NeighboursO(n log n)O(log n)
BetterLSD Radix Sort (Base 256)O(4·(n + 256))O(n)
OptimalPigeonhole Buckets (Min/Max Only)O(n)O(n)
Common pitfalls
  • Bucket width of 0 when hi - lo < n - 1 — clamp it to at least 1.
  • Comparing only adjacent bucket indices instead of skipping empty buckets.
  • Not handling n < 2 or all-equal values (division by zero / wrong count).
Interview tips
  • Start with sort-and-scan, then ask whether O(n log n) is acceptable given the linear-time requirement.
  • Mention radix sort as a linear alternative before introducing buckets.
  • Prove the bucket trick with the average-gap lower bound; interviewers look for that argument.
Pattern
Bucket / pigeonhole by value range → need order statistics in O(n) when values span a known range.
My notes saved in this browser