Data Structures & AlgorithmsHardGATE CS · DSA
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 = 777, 0, 777, 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. 27 9
- B. 27 11
- C. 26 9
- D. 29 9
Correct answer: A. 27 9
Rounding mid UP is essential with lo = mid, otherwise the loop can stall when hi = lo + 1. Output: 27 9.
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
- Merge two sorted linked lists by relinking nodes (ties take the node from the first list). What is printed? python def merge(a, b): d = t…
- Binary search with mid = (lo + hi) // 2 (lo = 0, hi = n − 1, loop while lo ≤ hi) looks for 81 in [22, 26, 29, 31, 36, 38, 46, 51, 70, 81…
- The intervals [15, 16], [11, 16], [4, 9], [4, 8], [8, 12], [20, 22] are sorted by start and merged (intervals that touch, like [2, 4] and…
- For s = "cbbbccadbcdacd", what is the length of the longest substring with at most 2 distinct characters, and how many substrings (by…
- Keys 81, 25, 26, 79, 49, 55, 59, 93 are inserted in this order into an empty table of size 11 with h(k) = k mod 11 and linear probing…
- Only the lower triangle (including the diagonal) of a 10 × 10 matrix is stored COLUMN by column in a 1-D array B starting at B[0] (indices…