Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

Exponential search: double the bound i (1, 2, 4, …) until a[i] ≥ key or i passes the end, then binary-search the last range. How many array probes are made in the doubling phase, and what index is returned?

Exponential search: double the bound i (1, 2, 4, …) until a[i] ≥ key or i passes the end, then binary-search the last range. How many array probes are made in the doubling phase, and what index is returned?
import bisect
a, key = [60, 62, 65, 75, 78, 88, 94, 95, 108, 109, 111, 115, 125, 138, 140, 146, 154, 183, 190, 195], 183
i, probes = 1, 0
while i < len(a):
    probes += 1
    if a[i] >= key: break
    i *= 2
lo, hi = i // 2, min(i, len(a) - 1)
idx = bisect.bisect_left(a, key, lo, hi + 1)
print(probes, idx if idx < len(a) and a[idx] == key else -1)
  1. A. 9 17
  2. B. 6 17
  3. C. 5 17
  4. D. 7 17

Correct answer: C. 5 17

Doubling finds a range of size about the key's position in O(log pos) probes, then binary search finishes it. Output: 5 17.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic