Data Structures & AlgorithmsHardGATE CS · DSA

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 = [6, 7, 10, 18, 28, 32, 43, 45, 50, 56, 62, 71, 72, 98, 145, 149, 173, 179, 182, 197], 173
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. 5 16
  2. B. 5 17
  3. C. 7 16
  4. D. 9 16

Correct answer: A. 5 16

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

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

Exams that ask this topic