Data Structures & AlgorithmsModerateProduct Company SDE · binary search warm-up

Problem: What is the integer floor of the square root of 10^12? Use binary search.

Problem: What is the integer floor of the square root of 10^12? Use binary search.
lo, hi = 0, 10 ** 12
while lo < hi:
    mid = (lo + hi + 1) // 2
    if mid * mid <= 10 ** 12:
        lo = mid
    else:
        hi = mid - 1
print(lo)
What is printed?
  1. A. 999999
  2. B. 1000000
  3. C. 1000001
  4. D. 10000000

Correct answer: B. 1000000

(10^6)^2 = 10^12 exactly, so the floor square root is 10^6. The mid value must be rounded up to avoid an infinite loop.

More Coding Interview Problems questions

Exams that ask this topic