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 - Optimal Solution INPUT nums = [3, 6, 9, 1] 3 idx 0 6 idx 1 9 idx 2 1 idx 3 (unsorted array) Requirements: - O(n) time complexity - O(n) space complexity - Find max gap in sorted form min = 1, max = 9 n = 4 elements ALGORITHM STEPS 1 Bucket Sort Setup bucketSize = (9-1)/(4-1) = 2.67 2 Place in Buckets Track min/max per bucket Bucket 0 1, 3 min:1 max:3 Bucket 1 6 min:6 max:6 Bucket 2 9 min:9 max:9 3 Find Max Gap Compare adjacent bucket gaps Gap 0-1: min(B1) - max(B0) = 6 - 3 = 3 Gap 1-2: min(B2) - max(B1) = 9 - 6 = 3 4 Return Maximum maxGap = max(3, 3) = 3 FINAL RESULT Sorted Array: 1 3 6 9 gap=2 gap=3 gap=3 Maximum Gap 3 [OK] Verified 3-1=2, 6-3=3, 9-6=3 Key Insight: Bucket/Radix sort achieves O(n) time. The maximum gap must occur between adjacent buckets, not within a bucket. By making bucket size = (max-min)/(n-1), we guarantee the max gap spans buckets. We only need to track min/max per bucket, reducing space while maintaining linear complexity. TutorialsPoint - Maximum Gap | Bucket Sort Approach
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