Maximum Gap - Problem
Find the Maximum Gap in Sorted Elements

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
Maximum Gap - Bucket Sort VisualizationBucket 1: [1,3)Numbers: 1Min: 1, Max: 1Bucket 2: [3,6)Numbers: 3Min: 3, Max: 3Bucket 3: [6,9]Numbers: 6,9Min: 6, Max: 91369Gap: 2Gap: 3Maximum Gap = 3Found between Bucket 2 and Bucket 3๐Ÿ”‘ Key Insight: Max gap always occurs BETWEEN buckets!Time: O(n) | Space: O(n)
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Need space for n-1 buckets, each storing min and max values

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค nums[i] โ‰ค 109
  • Must solve in O(n) time and O(n) space
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
98.4K Views
Medium Frequency
~25 min Avg. Time
2.2K 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