progress

~/problems / Binary search / Binary search on the answer

Sqrt(x)

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Write integer_sqrt(x: int) -> int that returns the largest whole number r with r * r <= x.

Integers only: no math.isqrt, math.sqrt or ** 0.5 (floats are off by one here anyway).

integer_sqrt(8)                    # 2      (2 * 2 = 4 <= 8 < 9)
integer_sqrt(16)                   # 4
integer_sqrt(0)                    # 0
integer_sqrt(10**18)               # 1000000000
integer_sqrt(10**18 - 1)           # 999999999

0 <= x <= 10^18, so counting r up one at a time is too slow even for the examples. ⭐ Bonus: a speed test with 20,000 large calls earns a star at O(log x) per call. In C++/Java, compare r <= x / r to avoid overflow.

Show hint

if r * r > x, everything above r fails too; otherwise everything below works.

Topic: Binary search on the answer. Monotonic feasibility check + search the smallest value that works.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc