Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole: the gap is never inside one bucket).

Problem: Find the maximum difference between successive values in the SORTED order of an array, in linear time, using buckets (pigeonhole: the gap is never inside one bucket).
def max_gap(a):
    lo, hi, n = min(a), max(a), len(a)
    if lo == hi: return 0
    size = max(1, (hi - lo) // (n - 1)); cnt = (hi - lo) // size + 1
    mins = [None] * cnt; maxs = [None] * cnt
    for x in a:
        i = (x - lo) // size
        mins[i] = x if mins[i] is None else min(mins[i], x)
        maxs[i] = x if maxs[i] is None else max(maxs[i], x)
    best, prev = 0, lo
    for i in range(cnt):
        if mins[i] is None: continue
        best = max(best, mins[i] - prev); prev = maxs[i]
    return best
print(max_gap([13, 1, 29, 7, 30, 18]), max_gap([5, 5, 5]))
What is printed?
  1. A. 6 0
  2. B. 11 5
  3. C. 12 0
  4. D. 11 0

Correct answer: D. 11 0

With n values over the range [lo, hi], the maximum gap is at least (hi − lo)/(n − 1), so with buckets of that width the answer is always between consecutive non-empty buckets: only each bucket's min and max matter. Sorted: 1, 7, 13, 18, 29, 30 → gaps 6, 6, 5, 11, 1 → 11. All equal → 0. O(n) time and space, versus O(n log n) for sorting.

More Coding Interview Problems questions

Exams that ask this topic