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.
Example 1:
Input: nums = [3,6,9,1] Output: 3 Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: nums = [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 1050 <= nums[i] <= 109The key challenge in #164 Maximum Gap is to find the maximum difference between adjacent elements in the sorted order of an array, without explicitly sorting it in O(n log n) time. A common optimization uses the Pigeonhole Principle with a bucket-based strategy.
First, identify the global min and max values. If there are n elements, the minimum possible maximum gap must be at least (max - min) / (n - 1). This observation allows us to divide the range into buckets where each bucket stores only the minimum and maximum value encountered. Since the maximum gap cannot occur inside a bucket, we only compare the boundaries between consecutive non-empty buckets.
This approach avoids full sorting and achieves near-linear performance. Alternatively, Radix Sort can also be used to sort numbers in linear time before computing adjacent differences. The bucket-based technique typically yields O(n) time with O(n) extra space.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Bucket-Based Gap Calculation | O(n) | O(n) |
| Radix Sort + Scan | O(n) | O(n) |
| Standard Sorting + Scan | O(n log n) | O(1) to O(n) |
NeetCode
The simplest approach to solve this problem is to first sort the array. Once sorted, the maximum gap will be found between consecutive elements. By iterating over the sorted array and computing the difference between each pair of consecutive elements, we can find the maximum difference.
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1) as no additional space is used except for variables.
1using System;
2
3public class Solution {
4 public int MaximumGap(int[] nums) {
5 if (nums.Length < 2) return 0;
6 Array.Sort(nums);
7 int maxGap = 0;
8 for (int i = 1; i < nums.Length; i++) {
9 maxGap = Math.Max(maxGap, nums[i] - nums[i - 1]);
10 }
11 return maxGap;
12 }
13}C#'s Array.Sort is used to sort the numbers. The algorithm then computes the maximum difference between consecutive sorted numbers.
This approach leverages the bucket sort idea to achieve linear time complexity. By calculating the bucket size and distributing array elements across buckets, we attempt to isolate maximum differences across distinct buckets, as adjacent elements within a bucket should have a smaller difference.
Time Complexity: O(n) since the bucket placement and scanning are linear operations.
Space Complexity: O(n) for the two bucket arrays.
1#include <vector>
#include <algorithm>
#include <limits>
int maximumGap(std::vector<int>& nums) {
if (nums.size() < 2) return 0;
int minVal = *std::min_element(nums.begin(), nums.end());
int maxVal = *std::max_element(nums.begin(), nums.end());
int bucketSize = std::max(1, (maxVal - minVal) / ((int)nums.size() - 1));
int bucketCount = (maxVal - minVal) / bucketSize + 1;
std::vector<int> minBucket(bucketCount, std::numeric_limits<int>::max());
std::vector<int> maxBucket(bucketCount, std::numeric_limits<int>::min());
for (int num : nums) {
int idx = (num - minVal) / bucketSize;
minBucket[idx] = std::min(minBucket[idx], num);
maxBucket[idx] = std::max(maxBucket[idx], num);
}
int maxGap = 0, prev = minVal;
for (size_t i = 0; i < minBucket.size(); ++i) {
if (minBucket[i] == std::numeric_limits<int>::max()) continue;
maxGap = std::max(maxGap, minBucket[i] - prev);
prev = maxBucket[i];
}
return maxGap;
}Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Yes, variations of the Maximum Gap problem appear in technical interviews because it tests understanding of linear-time sorting techniques and bucket-based reasoning. Interviewers often expect candidates to move beyond basic sorting and explain the bucket approach.
The optimal approach uses a bucket-based strategy derived from the pigeonhole principle. By distributing numbers into value ranges and tracking only bucket minimums and maximums, the algorithm finds the largest gap between consecutive buckets in linear time.
Yes, you can sort the array first and then compute the difference between adjacent elements. However, this approach takes O(n log n) time, which is slower than the optimal bucket or radix-based solutions.
Bucket sort works well because the maximum gap cannot occur within a bucket if the bucket size is chosen correctly. Instead, the gap must occur between the maximum of one bucket and the minimum of the next non-empty bucket.
This C++ solution uses a bucket sort-based approach. Buckets are determined based on the range and distributed among captured minimum and maximum bucket values, enabling the detection of the largest maximum gap across non-empty bucket sequences.