Maximum Gap - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [3,6,9,1]
›
Output:
3
💡 Note:
Sorted array is [1,3,6,9]. Gaps are: 3-1=2, 6-3=3, 9-6=3. Maximum gap is 3.
Example 2 — Larger Gap at End
$
Input:
nums = [10]
›
Output:
0
💡 Note:
Array has less than 2 elements, so return 0.
Example 3 — Multiple Large Gaps
$
Input:
nums = [1,10000000]
›
Output:
9999999
💡 Note:
Only two elements, so maximum gap is 10000000 - 1 = 9999999.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Unsorted integer array
2
Sort
Arrange elements in ascending order
3
Find Gap
Calculate maximum difference between consecutive elements
Key Takeaway
🎯 Key Insight: Use bucket sort to achieve O(n) time - the maximum gap occurs between buckets, not within them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code