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
Maximum Gap Problem OverviewInput Array:3691↓ Sort ↓Sorted Array:1369gap=2gap=3gap=3Maximum Gap: 3
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
Asked in
Google 15 Amazon 12 Microsoft 8
32.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen