Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft
Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)?
Integer square root by binary search (largest m with m·m ≤ n). What is printed (root, iterations)?
n, lo, hi, it = 200, 0, 200, 0
while lo < hi:
it += 1
mid = (lo + hi + 1) // 2
if mid * mid <= n: lo = mid
else: hi = mid - 1
print(lo, it)- A. 14 8
- B. 14 9
- C. 14 10
- D. 14 7
Correct answer: A. 14 8
Rounding mid UP is essential with lo = mid, otherwise the loop can stall when hi = lo + 1. Output: 14 8.
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
- Items E, F, G, H, I, J are pushed onto an empty stack in this order, and a pop may happen at any time. Which pop order is NOT possible?
- 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…
- One Hoare partition with the FIRST element as pivot (i moves right while a[i] < pivot, j moves left while a[j] > pivot, swap while i < j…
- Can a string become a palindrome by deleting at most one character? Two pointers try skipping either side on the first mismatch. What is…
- Binary search with mid = (lo + hi) // 2 (lo = 0, hi = n − 1, loop while lo ≤ hi) looks for 16 in [18, 39, 40, 44, 45, 56, 60, 62, 70, 84…
- For the sorted array [3, 3, 4, 5, 5, 7, 7, 8, 8, 8, 8, 10] (0-based), what are lowerbound(5) (first index with value ≥ 5) and…