Data Structures & AlgorithmsModerateTCS NQT · binary search warm-up

Problem: What is floor(sqrt(2000)) found by binary search? Run the code.

Problem: What is floor(sqrt(2000)) found by binary search? Run the code.
lo, hi = 0, 2000
while lo < hi:
    mid = (lo + hi + 1) // 2
    if mid * mid <= 2000:
        lo = mid
    else:
        hi = mid - 1
print(lo)
What is printed?
  1. A. 44
  2. B. 45
  3. C. 43
  4. D. 2000

Correct answer: A. 44

44^2 = 1936 <= 2000 and 45^2 = 2025 > 2000, so the search converges to 44. Using the upper mid (lo + hi) // 2 without +1 can loop forever on this template.

More Coding Interview Problems questions

Exams that ask this topic