Skip to content
Problem 164 · LeetCode 164(opens in a new tab)

Maximum Gap

MediumArrays

You get an array of non-negative whole numbers, nums. Imagine it sorted from small to large and look at each pair of neighbours. Return the largest difference between two neighbours.

If the array has fewer than two numbers, there are no neighbours, so return 0. The follow-up asks for linear time and linear extra memory, so a plain sort is not the final answer.

Example 1

Input:  nums = [12, 3, 20, 7]
Output: 8
Why:    sorted it is 3, 7, 12, 20; the gaps are 4, 5, 8
2 more examples and the constraints

Example 2

Input:  nums = [42]
Output: 0
Why:    one number has no neighbour

Example 3

Input:  nums = [5, 5, 5]
Output: 0
Why:    equal numbers are 0 apart

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • 0 ≤ nums[i] ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Sort, then scanO(n log n)
  2. Buckets (pigeonhole)O(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Sort, then scanO(n log n)
Passes; misses the follow-up
Buckets (pigeonhole)O(n)
Best; linear time and space

n = length of nums.

Edge cases to test

  • One number. [42] has no pair: return 0 before dividing by n − 1.
  • All equal. [5, 5, 5] gives hi − lo = 0; size must be at least 1 to avoid dividing by zero.
  • Evenly spaced. [40, 10, 30, 20]: every gap equals size, and each number lands in its own bucket.
  • Huge values. Up to 1,000,000,000: hi − lo still fits in a 32-bit int.

Common mistakes

  • Looking at gaps between neighbours in the original order instead of the sorted order.
  • Comparing numbers inside one bucket, or using a bucket's min instead of its max as prev.
  • Forgetting max(1, …) for the bucket size, which divides by zero when all numbers are equal.

How to talk through it

  1. 1Clarify. Neighbours in sorted order, right? What do I return for one number? Are values non-negative?
  2. 2Give the sort. Sort and scan: O(n log n), correct, and the baseline.
  3. 3Find a lower bound. n − 1 gaps cover hi − lo, so the widest is at least their average.
  4. 4Bucket by that bound. Numbers in one bucket are closer than the bound, so keep only each bucket's min and max.
  5. 5Test out loud. Run one number, all equal numbers and an evenly spaced array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?