The Maximum Gap coding problem asks you to find the maximum difference between successive elements in the sorted form of an unsorted array. In other words, once you sort the array, what is the largest gap between any two consecutive numbers? The twist that makes this genuinely interesting is the constraint: you must solve it in O(n) time and O(n) space, which rules out standard comparison-based sorting.
Companies like Microsoft, Google, Meta, and Amazon include Maximum Gap in their interview sets because it probes knowledge of non-comparison-based sorting algorithms. Most candidates default to quick sort or merge sort; this problem forces you to think about bucket sort or radix sort. It also tests whether you understand the pigeonhole principle as a mathematical tool for bounding the answer — a level of reasoning that separates strong candidates from average ones.
The standard approach uses bucket sort combined with the pigeonhole principle. Given n elements spanning a range [min, max], the maximum gap must be at least ceil((max - min) / (n - 1)). You create n-1 buckets, each of size at least that minimum gap. For any two elements landing in the same bucket, their difference is smaller than the bucket size, so the maximum gap must span across at least one empty bucket. You only need to track the min and max of each bucket, then scan adjacent non-empty buckets to find the largest gap.
Array: [3, 6, 9, 1]
For the Array Bucket Sort Sorting Radix Sort interview pattern, memorize the bucket sort template for this problem type. The key insight to communicate in interviews is the pigeonhole principle argument: "If I have n-1 buckets and n elements, at least one bucket must contain two elements, so the max gap cannot come from within a bucket." This explanation demonstrates mathematical maturity and impresses interviewers.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sort the Jumbled Numbers | Medium | Solve | |
| Check if Grid can be Cut into Sections | Medium | Solve | |
| Count Days Without Meetings | Medium | Solve | |
| Sort an Array | Medium | Solve | |
| Remove Covered Intervals | Medium | Solve |