codejump
HardPro challengePythonJavaScriptTypeScript

Sorting — Maximum Gap (Bucket Sort)

AlgorithmsSortingBucket SortPigeonhole

solve(nums) — return the largest difference between two successive values of
nums once it is sorted. Fewer than two values means 0. Sorting gives O(n log n);
the interview version asks for O(n) time.

Use the pigeonhole principle. With n values between min and max, the average gap
is (max - min) / (n - 1), so the maximum gap is at least that. Split the range into
buckets of that width: two values in the same bucket are closer than the answer, so the
answer is a gap *between* buckets. Keep only each bucket's min and max, then compare
every non-empty bucket's min with the previous non-empty bucket's max.

Examples

solve([3,6,9,1])      → 3
solve([10])           → 0
solve([100,3,2,1])    → 97
solve([1,1,1,1])      → 0

Sample tests

Test #1Classic example
Input: [[3,6,9,1]]
Output: 3
Test #2Single value
Input: [[10]]
Output: 0
Test #3One huge gap
Input: [[100,3,2,1]]
Output: 97