Maximum Gap - Problem
Find the Maximum Gap in Sorted Elements
You're given an unsorted integer array
๐ฏ The Challenge: You must solve this in linear time O(n) and use only linear extra space O(n)!
๐ Special Cases:
โข If the array has fewer than 2 elements, return
โข The array may contain duplicates
Example: For
You're given an unsorted integer array
nums, and your mission is to find the maximum difference between two successive elements when the array is sorted in ascending order.๐ฏ The Challenge: You must solve this in linear time O(n) and use only linear extra space O(n)!
๐ Special Cases:
โข If the array has fewer than 2 elements, return
0โข The array may contain duplicates
Example: For
[3, 6, 9, 1], when sorted becomes [1, 3, 6, 9], the successive differences are [2, 3, 3], so the maximum gap is 3. Input & Output
example_1.py โ Basic Case
$
Input:
nums = [3, 6, 9, 1]
โบ
Output:
3
๐ก Note:
When sorted, the array becomes [1, 3, 6, 9]. The successive differences are [2, 3, 3], and the maximum is 3.
example_2.py โ All Same Elements
$
Input:
nums = [10]
โบ
Output:
0
๐ก Note:
The array has only one element, so there are no successive pairs to compare.
example_3.py โ Large Gap
$
Input:
nums = [1, 1000000]
โบ
Output:
999999
๐ก Note:
When sorted, it's still [1, 1000000]. The gap between successive elements is 1000000 - 1 = 999999.
Visualization
Tap to expand
Understanding the Visualization
1
Find Range
Determine the range from minimum to maximum value
2
Create Buckets
Create n-1 buckets to distribute n numbers
3
Fill Buckets
Place numbers in appropriate buckets, storing only min/max per bucket
4
Find Max Gap
The answer is the maximum gap between consecutive non-empty buckets
Key Takeaway
๐ฏ Key Insight: By using the pigeonhole principle with n-1 buckets for n numbers, we guarantee that the maximum gap occurs between buckets, not within them. This allows us to solve the problem in linear time!
Time & Space Complexity
Time Complexity
O(n)
Single pass to find min/max, single pass to fill buckets, single pass to find max gap
โ Linear Growth
Space Complexity
O(n)
Need space for n-1 buckets, each storing min and max values
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 109
- Must solve in O(n) time and O(n) space
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code