#164
Maximum Gap
MediumArraySortingBucket SortRadix SortBucket SortArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses the concept of bucket sort to find the maximum gap without sorting the entire array. This method is efficient and runs in linear time.
⚙️
Algorithm
4 steps- 1Step 1: Find the minimum and maximum values in the array.
- 2Step 2: Calculate the bucket size and the number of buckets needed.
- 3Step 3: Place each number in the appropriate bucket.
- 4Step 4: Calculate the maximum gap by checking the maximum difference between the minimum of the next bucket and the maximum of the current bucket.
solution.py23 lines
1# Full working Python code
2
3def maximum_gap(nums):
4 if len(nums) < 2:
5 return 0
6 min_val, max_val = min(nums), max(nums)
7 if min_val == max_val:
8 return 0
9 bucket_size = max(1, (max_val - min_val) // (len(nums) - 1))
10 bucket_count = (max_val - min_val) // bucket_size + 1
11 buckets = [[float('inf'), float('-inf')] for _ in range(bucket_count)]
12 for num in nums:
13 idx = (num - min_val) // bucket_size
14 buckets[idx][0] = min(buckets[idx][0], num)
15 buckets[idx][1] = max(buckets[idx][1], num)
16 max_gap = 0
17 previous_max = min_val
18 for bucket in buckets:
19 if bucket[0] == float('inf'):
20 continue
21 max_gap = max(max_gap, bucket[0] - previous_max)
22 previous_max = bucket[1]
23 return max_gapℹ
Complexity note: The time complexity is O(n) because we only traverse the array a constant number of times. The space complexity is O(n) due to the additional space used for the buckets.
- 1Understanding the relationship between the range of numbers and the number of buckets is crucial.
- 2The maximum gap can only occur between the maximum of one bucket and the minimum of the next non-empty bucket.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.