InterviewPrepKit

Home / Coding / Binary Search

Sqrt(x)

easy Original ↗
Solving tips
  • Recognize 'binary search on the answer': the predicate r*r <= x is monotone (True then False), so search the value range [0,x] rather than any array.
  • At each mid, if mid*mid <= x remember it as the answer and go higher, else go lower; the last feasible mid is the integer square root.
  • Target O(log x) time, O(1) space; Newton's iteration r = (r + x//r)//2 converges even faster (O(log log x)-ish) and is the classic alternative.
  • Pitfalls: return the last r with r*r <= x (sqrt(8)=2 not 3), and in fixed-width languages mid*mid can overflow, compare mid <= x/mid instead.

Problem

Given a non-negative integer x, compute the integer square root of x: the largest non-negative integer r such that r * r <= x. In other words, return the square root of x rounded down to the nearest integer.

You may not use any built-in exponent function or operator such as pow(x, 0.5) or x ** 0.5.

Examples

  • Input: x = 4 → Output: 2 (2 * 2 = 4 exactly.)
  • Input: x = 8 → Output: 2 (sqrt(8) ≈ 2.828…; rounding down gives 2, and indeed 2² = 4 ≤ 8 < 9 = 3².)
  • Input: x = 1 → Output: 1 (1 * 1 = 1 ≤ 1; edge values 0 and 1 are their own answers.)

Constraints

  • 0 <= x <= 2^31 - 1
  • No built-in exponent/sqrt functions.
  • x up to ~2.1 billion means the answer can be up to 46340, and a solution should be logarithmic (or otherwise far better than trying every candidate).

Think about it first

Hint 1 You're looking for a number `r` with `r² <= x < (r+1)²`. As `r` grows, does `r² <= x` ever flip from False back to True?
Hint 2 The predicate `r² <= x` is True for all small `r` and False for all large `r` — a monotone boundary. You know an algorithm that finds such a boundary in O(log) steps without ever computing a square root.
Hint 3 Binary search `r` over `[0, x]`: if `mid² <= x`, `mid` is feasible — remember it and search higher; otherwise search lower. The last feasible `mid` is the answer. (Newton's iteration `r = (r + x // r) // 2` is the other classic route.)
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.