↓Skip to main content
  1. LeetCode/

LeetCode 164: Maximum Gap

·3 mins· ·
LeetCode Medium Bucket-Sort Radix-Sort Sorting Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-04-14

  • Submissions: Runtime Error → Accepted (sorting) → Memory Limit Exceeded ×2 (2025-04-15, 2025-04-20)

Approach
#

The problem asks for linear time, so no sorting. Use the pigeonhole principle (Bucket Sort):

  • With n numbers in [lo, hi], the n - 1 sorted adjacent differences sum to hi - lo, so the maximum difference is at least the average (hi - lo) / (n - 1).
  • Split the range into buckets no wider than the average; two numbers in one bucket differ by less than the average, so that cannot be the maximum.
  • So the maximum is “some non-empty bucket’s minimum minus the previous non-empty bucket’s maximum”, and each bucket only needs its minimum and maximum.

My Attempts
#

  1. Attempt 1 simply sorted; an extra parenthesis gave RE, and the fixed version passed, but that is O(n log n), not what the problem asks.
  2. Later, aiming for linear time, I allocated a boolean array as large as the value range to mark values seen, then scanned it for the largest gap. Values reach 10^9, so both tries hit Memory Limit Exceeded.
  3. The right approach makes the number of buckets depend on n, not on the value range.

Solution
#

class Solution:
    def maximumGap(self, nums: List[int]) -> int:
        lo, hi, n = min(nums), max(nums), len(nums)
        if n < 2 or lo == hi:
            return 0
        size = max(1, (hi - lo) // (n - 1))        # bucket width at most the average gap
        count = (hi - lo) // size + 1
        bmin, bmax = [None] * count, [None] * count
        for x in nums:
            b = (x - lo) // size
            bmin[b] = x if bmin[b] is None else min(bmin[b], x)
            bmax[b] = x if bmax[b] is None else max(bmax[b], x)
        best, prev = 0, lo
        for b in range(count):
            if bmin[b] is not None:
                best = max(best, bmin[b] - prev)
                prev = bmax[b]
        return best

Complexity
#

Time O(n), space O(n).

Mistakes to Avoid
#

  • Do not allocate an array the size of the value range.
  • Compute the bucket width with integer division clamped to at least 1, so it is never 0.
  • Compare only consecutive non-empty buckets; skip empty ones.

Interview Explanation
#

The maximum gap is at least the average gap, so I split the range into buckets no wider than the average; a difference within one bucket cannot be the maximum. Each bucket keeps its minimum and maximum, and one final scan takes each non-empty bucket’s minimum minus the previous non-empty bucket’s maximum. Time and space O(n).

Related

LeetCode 3075: Maximize Happiness of Selected Children
·1 min
LeetCode Medium Array Greedy Sorting
LeetCode 3075 note: choose k children from the happiest, where the i-th choice loses i, floored at 0
LeetCode 324: Wiggle Sort II
·2 mins
LeetCode Medium Array Divide-and-Conquer Greedy Sorting
LeetCode 324 note: sort, split into a small half and a large half, reverse each, and interleave with small values at even indices and large ones at odd indices
LeetCode 435: Non-overlapping Intervals
·2 mins
LeetCode Medium Array Dynamic-Programming Greedy Sorting
LeetCode 435 note: minimum removals = total minus the maximum kept; sort by right end and greedily keep the one ending earliest
LeetCode 229: Majority Element II
·2 mins
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 note: at most two values can exceed n / 3; Boyer-Moore keeps two candidates and a second pass verifies their counts
LeetCode 215: Kth Largest Element in an Array
·2 mins
LeetCode Medium Array Divide-and-Conquer Sorting Heap-Priority-Queue
LeetCode 215 note: keep a min-heap of size k whose top is the k-th largest, or use quickselect for O(n) on average
LeetCode 347: Top K Frequent Elements
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 note: count first, then take the k most frequent with a size-k heap or a bucket sort indexed by count