medium Sqrt
Problem Statement
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator.
For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.
Example 1:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.8284, and since we need to return the floor of the square root (integer), hence we returned 2.
Example 2:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.
Example 3:
Input: x = 2
Output: 1
Explanation: The square root of 2 is 1.414, and since we need to return the floor of the square root (integer), hence we returned 1.
Constraints:
- 0 <= x <= 231 - 1
Try it yourself
Try solving this question here:
For a detailed solution, see the next chapter.
✅ Solution Sqrt
Problem Statement
Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.
You must not use any built-in exponent function or operator. For example, do not use pow(x, 0.5) in C++ or x ** 0.5 in Python.
Example 1:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.8284, and since we need to return the floor of the square root (integer), hence we returned 2.
Example 2:
Input: x = 4
Output: 2
Explanation: The square root of 4 is 2.
Example 3:
Input: x = 2
Output: 1
Explanation: The square root of 2 is 1.414, and since we need to return the floor of the square root (integer), hence we returned 1.
Constraints:
- 0 <= x <= 231 - 1
Solution
We can use a Binary Search approach to calculate the square root of an integer x without using any in-built sqrt function.
For any integer x, the square root of x will lie between 0 and x/2 (inclusive) for x > 2. Therefore, we can efficiently use binary search within this range to find the integer part of the square root (i.e., the floor value). By narrowing down the potential values step-by-step, binary search allows us to determine the largest integer y such that y*y is less than or equal to x.
This approach ensures an efficient and accurate computation of the square root, especially for large values of x, due to the logarithmic nature of binary search.
Step-by-Step Algorithm
- Handle Base Cases: If
xis less than 2, returnxdirectly (since the square root of 0 is 0, and the square root of 1 is 1). - Initialize Pointers: Set
leftto 2 andrighttox / 2. - Binary Search Loop:
- While
leftis less than or equal toright:- Calculate
midasleft + (right - left) // 2. - Calculate
numasmid * mid. - If
numis greater thanx, moverighttomid - 1. - If
numis less thanx, movelefttomid + 1. - If
numequalsx, returnmid.
- Calculate
- While
- Return Result: Return
rightas the integer part of the square root ofx.
Algorithm Walkthrough
Let's consider the input n = 8:
-
Initialize:
- Input
x = 8. - Since
xis not less than 2, proceed to the next step. - Set
left = 2andright = 4(8 // 2).
- Input
-
First Iteration:
- Calculate
mid = 2 + (4 - 2) // 2 = 3. - Calculate
num = 3 * 3 = 9. - Since
num(9) is greater thanx(8), moverighttomid - 1 = 2.
- Calculate
-
Second Iteration:
- Now
left = 2andright = 2. - Calculate
mid = 2 + (2 - 2) // 2 = 2. - Calculate
num = 2 * 2 = 4. - Since
num(4) is less thanx(8), movelefttomid + 1 = 3.
- Now
-
End Loop:
- Now
left = 3andright = 2. - Since
left(3) is greater thanright(2), exit the loop.
- Now
-
Return Result:
- Return
right = 2as the integer part of the square root ofx = 8.
- Return
Code
Here is the code for this algorithm:
class Solution {
public int mySqrt(int x) {
if (x < 2) return x; // return x if it is 0 or 1
int left = 2,
right = x / 2;
int mid;
long num;
while (left <= right) {
// binary search for the square root
mid = left + (right - left) / 2;
num = (long) mid * mid;
if (num > x) right = mid - 1;
// if mid * mid is greater than x, set right to mid - 1
else if (num < x) left = mid + 1;
// if mid * mid is less than x, set left to mid + 1
else return mid; // if mid * mid is equal to x, return mid
}
return right;
}
public static void main(String[] args) {
Solution solution = new Solution();
int input1 = 4;
int expectedOutput1 = 2;
int result1 = solution.mySqrt(input1);
System.out.println(result1 == expectedOutput1); // Expected output: true
int input2 = 8;
int expectedOutput2 = 2;
int result2 = solution.mySqrt(input2);
System.out.println(result2 == expectedOutput2); // Expected output: true
int input4 = 2;
int expectedOutput4 = 1;
int result4 = solution.mySqrt(input4);
System.out.println(result4 == expectedOutput4); // Expected output: true
int input5 = 3;
int expectedOutput5 = 1;
int result5 = solution.mySqrt(input5);
System.out.println(result5 == expectedOutput5); // Expected output: true
int input6 = 15;
int expectedOutput6 = 3;
int result6 = solution.mySqrt(input6);
System.out.println(result6 == expectedOutput6); // Expected output: true
}
}
Complexity Analysis
Time Complexity
-
Binary Search Algorithm: The key part of this algorithm is the binary search, which repeatedly divides the search interval in half. The time complexity of binary search is
, where is the size of the search space. In this case, the search space is initially from 2tox/2. -
Search Space: The maximum size of the search space is
x/2(when). For smaller values of x, the function immediately returnsx, as it's either0or1. -
Overall Time Complexity: Considering the binary search on a range up to
x/2, the time complexity is, which simplifies to .
Space Complexity
-
Constant Extra Space: The algorithm uses a fixed number of integer variables (
left,right,pivot,num), regardless of the input size. -
No Recursive Calls or Dynamic Allocation: The implementation does not use recursion or allocate additional data structures that grow with the input size.
-
Overall Space Complexity: Given the constant amount of extra space, the space complexity is
, meaning it's constant.
🤖 Don't fully get this? Learn it with Claude
Stuck on Sqrt? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Sqrt** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Sqrt** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Sqrt**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Sqrt**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.