#69

Sqrt(x)

Easy Binary search on the answer

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the integer square root of x (rounded down) without using a built-in power or sqrt function.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the biggest r with r × r ≤ x.

Why this works: "r² ≤ x" is true then false as r grows, so binary search r. Compare mid ≤ x / mid to avoid overflow.

Example: x = 8

mid 2: 2 ≤ 4 ✓ → ans 2, go rightmid 3: 3 ≤ 2 ✗ → go leftanswer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Computing mid * mid in int, which overflows for x near 2^31.

Solve on LeetCode ↗
Complexity
  • Time: O(log x).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon