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 = [23, 30, 54, 69, 74, 80, 84, 90, 119, 126, 127, 134, 142, 153, 154, 156, 159, 161, 179, 194], 159
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. 7 16
  2. B. 9 16
  3. C. 5 16
  4. D. 4 16

Correct answer: C. 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