AlgoInsight

DSA problem

Maximum Gap

MediumBucket SortPattern: Bucket Sorttop300AmazonGoogleMicrosoftAppleBloomberg

Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0. You must write an algorithm that runs in linear time and uses linear extra space.

The trivial solution sorts the array and scans neighboring pairs, but that costs O(n log n) and violates the constraint. To achieve linear time you must avoid any general comparison sort.

The key insight is pigeonhole bucketing. Suppose nums has n elements with minimum minV and maximum maxV. After sorting, the n - 1 consecutive gaps sum to maxV - minV, so by the pigeonhole principle the maximum gap is at least ceil((maxV - minV) / (n - 1)). Choose this value as the bucket size. Two numbers that fall into the same bucket therefore differ by strictly less than the bucket size, which means the answer cannot be a within-bucket difference — it must be a between-bucket difference.

Allocate n buckets indexed by (num - minV) / bucketSize. For each bucket store only its current minimum and maximum (no need to store every element). Then scan the buckets in order, tracking the maximum of the previous non-empty bucket; the gap is bucket.min - prevMax. Update prevMax to the current bucket's maximum and continue. The total work is O(n) time and O(n) space — exactly what the problem demands.

Examples

Example 1
Input: nums = [3,6,9,1]
Output: 3
Explanation: Sorted the array is [1,3,6,9] with consecutive gaps of 2, 3, and 3. The maximum is 3.
Example 2
Input: nums = [10]
Output: 0
Explanation: A single-element array has no pair of successive elements, so the answer is 0 by definition.
Example 3
Input: nums = [1,10000000]
Output: 9999999
Explanation: With only two elements the gap is simply their difference; the bucket method still returns the correct answer.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bucket-sortarraysortingradix-sort

Browse all DSA problems