#164

Maximum Gap

Medium Bucket sort (pigeonhole)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the largest difference between consecutive elements after sorting, in linear time and space. Return 0 for fewer than two elements.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the biggest gap between neighbours after sorting, in O(n).

Why this works: with n numbers spread over [min, max], the biggest gap is at least (max-min)/(n-1). Buckets that small can't contain the biggest gap, so only compare between buckets.

Example: [3, 6, 9, 1] → min 1, max 9, bucket size 3

buckets: [1,3], [6], [9]gaps: 6-3 = 3, 9-6 = 3 → answer 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

A bucket size of 0 when all values are equal — use at least 1.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Sorting
🎬 Episodes 24–28: video coming soon