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?- A. 6 0
- B. 11 5
- C. 12 0
- 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
- Problem: Camera clips (start, end) cover parts of an event lasting T = 10 minutes; clips may be trimmed. Find the minimum number of clips…
- Problem: A broken calculator shows start and supports only 'double' and 'decrement by 1'. Find the minimum operations to reach target…
- Problem: Return the largest number ≤ n whose digits are non-decreasing from left to right. python def mono(n): d = list(str(n)); mark =…
- Problem: A string has '(', ')' and '', where '' may act as '(', ')' or nothing. Is it balanceable? Track the range [lo, hi] of possible…
- Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag…
- Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move. python moves = [] def hanoi(n, a, b, c): if n ==…