Skip to content
Problem 69 · LeetCode 69(opens in a new tab)

Sqrt(x)

EasyBinary search

You are given a whole number x that is 0 or more. Return its square root, rounded down to a whole number. In other words, return the largest k with k × k ≤ x.

Do not use a built-in power or square-root function, such as pow(x, 0.5) or Math.sqrt(x). Work it out with plain arithmetic.

Example 1

Input:  x = 15
Output: 3
Why:    3 × 3 = 9 fits under 15, but 4 × 4 = 16 is too big
2 more examples and the constraints

Example 2

Input:  x = 49
Output: 7
Why:    49 is a perfect square, 7 × 7

Example 3

Input:  x = 0
Output: 0
Why:    0 × 0 = 0

Constraints

  • 0 ≤ x ≤ 2,147,483,647 (the largest 32-bit signed int)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count upO(√x)
  2. Binary searchO(log x)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for x = 2,147,483,647Verdict
Count upO(√x)
Mention it, then move on
Binary searchO(log x)
Best; about 31 rounds

x = the input number.

Edge cases to test

  • Zero and one. Both are their own root. With lo = 0 and hi = x the loop does not even start.
  • Perfect squares. 100 must give 10, not 9: the test is ≤, not <.
  • Just under a square. 99 gives 9, because 10 × 10 = 100 is too big.
  • The largest input. 2,147,483,647 gives 46,340. Squaring numbers this big overflows a 32-bit int.

Common mistakes

  • Squaring mid in a 32-bit int, which overflows and makes a big mid look small.
  • Using mid = (lo + hi) / 2 with lo = mid, which loops forever when hi = lo + 1.
  • Writing mid * mid < x, which returns 9 instead of 10 for x = 100.

How to talk through it

  1. 1Clarify. Rounded down, not to the nearest? Can x be 0? No built-in square root, right?
  2. 2Give the simple scan. Count k up while the next square fits. Say it is O(√x), about 46,000 steps at the top.
  3. 3Spot the order. Squares only grow, so the numbers that fit come first. That is the cue for binary search on the answer.
  4. 4Code the search. Keep mid when it fits, drop it when it does not, round mid up, and use 64-bit math for the square.
  5. 5Test out loud. Run 0, 1, a perfect square like 100 and the largest input before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?