Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Exponential (galloping) search: double the bound until a[hi] ≥ target, then binary search in (hi/2, hi]. Count the comparisons of the doubling phase and the result.
Problem: Exponential (galloping) search: double the bound until a[hi] ≥ target, then binary search in (hi/2, hi]. Count the comparisons of the doubling phase and the result.
from bisect import bisect_left
a = list(range(0, 3000, 3)) # 0, 3, 6, ..., 2997
def gallop(t):
hi, steps = 1, 0
while hi < len(a) and a[hi] < t: hi *= 2; steps += 1
lo = hi // 2; hi = min(hi, len(a) - 1)
i = bisect_left(a, t, lo, hi + 1)
return steps, (i if i < len(a) and a[i] == t else -1)
print(*gallop(600), *gallop(601))What is printed?- A. 8 200 8 -1
- B. 7 200 7 -1
- C. 8 200 8 201
- D. 8 199 8 -1
Correct answer: A. 8 200 8 -1
600 sits at index 200. Doubling 1, 2, 4, …, 256 takes 8 steps (a[128] = 384 < 600, a[256] = 768 ≥ 600), then binary search in [128, 256] finds 200. 601 is not a multiple of 3, so it is absent (−1). Cost O(log i) where i is the answer's index.
More Coding Interview Problems questions
- Problem: Count unique quadruplets (as value multisets) summing to target with sort + two nested loops + two pointers. python def four(a…
- Problem: For each element, the nearest smaller value to its LEFT (−1 if none), with a monotonic stack. python def leftsmaller(a): st, out…
- Problem: Report the first negative number in every window of size k (0 if none), using a queue of negative indices. python from…
- Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge). python…
- Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values). python class N: def…
- Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent). python class T: def init(s, v): s.v, s.l…