Data Structures & AlgorithmsVery hardProduct company OA
A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed?
A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed?
def search(a, x):
lo, hi, steps = 0, len(a) - 1, 0
while lo < hi and steps < 50:
steps += 1
mid = (lo + hi) // 2
if a[mid] <= x: lo = mid
else: hi = mid - 1
return lo, steps
a = [1, 3, 5, 7, 9, 11]
print(search(a, 3), search(a, 7), search(a, 11))- A. (0, 50) (3, 3) (4, 50)
- B. (1, 2) (3, 3) (5, 3)
- C. (0, 50) (3, 3) (5, 3)
- D. (1, 50) (3, 3) (4, 50)
Correct answer: A. (0, 50) (3, 3) (4, 50)
With mid = (lo + hi) // 2 and the update lo = mid, once hi = lo + 1 the midpoint equals lo; if a[mid] ≤ x, lo does not move and the loop never ends. x = 3: lo 0, hi 5 → hi 1 → mid 0 → lo stays 0 forever. x = 7 happens to finish at index 3. x = 11 reaches lo 4, hi 5 and sticks. The fix is the upper midpoint mid = (lo + hi + 1) // 2 whenever the branch is lo = mid.
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
- Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes…
- Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed? python from collections…
- Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking…
- Probe-sequence coverage for open addressing: how many distinct slots can the offsets i² (quadratic) and i(i+1)/2 (triangular) reach in…
- An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order? python from…
- Minimum number of brackets to INSERT to make a string balanced, returned as (total, unmatched ')', unmatched '('). What is printed? python…