Magicsheet logo

Sqrt(x)

Easy
50%
Updated 8/1/2025

Sqrt(x)

What is this problem about?

The Sqrt(x) interview question is a classic challenge: given a non-negative integer xx, find its square root rounded down to the nearest integer. You are essentially finding the largest integer nn such that n2xn^2 \le x. This is a baseline question for understanding how to search for values in a continuous or discrete mathematical range.

Why is this asked in interviews?

Companies like Google, Nvidia, and LinkedIn use this problem to see if a candidate understands the efficiency of different search algorithms. It's a perfect test of the Binary Search interview pattern. Interviewers also use it to check for "defensive programming"—handling edge cases and potential overflow issues that arise when squaring large numbers.

Algorithmic pattern used

Binary Search is the most efficient Algorithmic pattern for this problem. You treat the integers from 0 to xx as a sorted array. By checking the middle value mm and comparing m2m^2 with xx, you can discard half of the remaining numbers in each step. Alternatively, Newton's Method can be used, which is an iterative way to find roots using calculus, but binary search is more common in coding interviews.

Example explanation (use your own example)

Suppose you want the integer square root of 15.

  1. Start with a range [1, 15]. Middle is 8. 82=648^2 = 64, which is >15> 15.
  2. New range is [1, 7]. Middle is 4. 42=164^2 = 16, which is >15> 15.
  3. New range is [1, 3]. Middle is 2. 22=42^2 = 4, which is 15\le 15. Keep 2 as a candidate.
  4. New range is [3, 3]. Middle is 3. 32=93^2 = 9, which is 15\le 15. Keep 3 as a candidate. The next step would make the range empty. The largest candidate found was 3. Thus, the integer square root of 15 is 3.

Common mistakes candidates make

  • Overflowing the variable: Not using a long for the product of mid * mid in languages like Java or C++.
  • Wrong exit condition: Using while (low < high) and missing the case where low == high is the answer.
  • Linear approach: Using a loop that increments one by one, which fails for very large integers near 23112^{31}-1.
  • Not handling small xx: Failing on x=0x=0 or x=1x=1.

Interview preparation tip

When asked this Sqrt(x) coding problem, first mention the linear approach to show you understand the problem, then immediately explain why binary search is better (O(logN)O(\log N)). Mentioning Newton's Method can also show extra depth in your mathematical knowledge.

Similar Questions