Member-only story
π§βπ» LeetCode 0069 β Sqrt(x), All Solutions Explained with Java! π§
βThe journey of a thousand miles begins with one stepβ¦ or one square root.β
π Problem Overview
Given a non-negative integer x
, compute and return the square root of x
, rounded down to the nearest integer. You must not use any built-in exponent function or operator like Math.sqrt()
or x ** 0.5
.
Example:
Input: x = 8
Output: 2
Explanation: sqrt(8) β 2.828, so we return 2.
π οΈ Solution 1: Brute Force (Linear Search) π’
Idea
Try all integers i
starting from 0. Stop when i * i > x
. The previous i
will be the answer.
public int mySqrt(int x) {
if (x < 2) return x;
for (int i = 1; i <= x / 2; i++) {
if (i <= x / i && (i + 1) > x / (i + 1)) {
return i;
}
}
return 1;
}
β±οΈ Time Complexity:
- O(βx) β Worst case for very large x.
ποΈ Space Complexity:
- O(1) β Only constant extra space.
β οΈ Drawback:
- Not efficient for very large values of
x
.