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?
  1. A. 8 200 8 -1
  2. B. 7 200 7 -1
  3. C. 8 200 8 201
  4. 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

Exams that ask this topic