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)- A. 5 16
- B. 5 17
- C. 7 16
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- For an n × n matrix whose rows and columns are both sorted ascending, what is the time of the staircase search for a key?
- Swap every two adjacent nodes of a linked list by relinking (not by swapping values). What is printed? python def swappairs(h): d = p =…
- Partition a linked list around x: all nodes with value < x come first, then the rest, each part keeping its original relative order. What…
- Two ways of finding the middle of a linked list with slow/fast pointers. What is printed? python h = build([25, 47, 35, 52, 83, 28, 17…
- Evaluate the postfix expression 3 5 4 6 1 ÷ − + + (all divisions are exact). What is its value, and what is the maximum number of operands…
- Count palindromic substrings by expanding around all 2n − 1 centres, and also count DISTINCT palindromic substrings. What is printed?…