Difficulty | Source | Tags | |||
---|---|---|---|---|---|
Easy |
160 Days of Problem Solving (BONUS PROBLEMS 🎁) |
|
The problem can be found at the following link: Problem Link
Given a positive integer n
, find the square root of n
. If n
is not a perfect square, return the floor value.
The floor value of any number is the greatest integer which is less than or equal to that number.
Input:
n = 4
Output:
2
Explanation:
Since 4 is a perfect square, its square root is 2.
Input:
n = 11
Output:
3
Explanation:
Since 11 is not a perfect square, the floor of the square root of 11 is 3.
Input:
n = 1
Output:
1
Explanation:
Since 1 is a perfect square, the square root is 1.
$1 ≤ n ≤ 3 \times 10^4$
-
Binary Search Initialization:
We initialize two pointerslo
(low) andhi
(high), wherelo = 0
andhi = n
. -
Binary Search Loop:
We perform a binary search to find the integer square root ofn
. The middle elementmid
is computed as:mid = lo + (hi - lo) / 2
-
Check for Square:
Ifmid * mid <= n
, we update the result tomid
(since it is a valid candidate for the square root) and shift thelo
pointer tomid + 1
. Otherwise, we move thehi
pointer tomid - 1
. -
End Condition:
The loop continues untillo
exceedshi
, and at the end of the search, the value stored inans
will be the largest integer whose square is less than or equal ton
.
- Time Complexity: O(log n), where
n
is the number for which we are finding the square root. In each iteration of the binary search, we are halving the search space. - Auxiliary Space Complexity: O(1), as we only use a few integer variables for the binary search and result tracking.
int floorSqrt(int n) {
int lo = 0, hi = n, ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if ((long long)mid * mid <= n) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
class Solution {
public:
int floorSqrt(int n) {
int lo = 0, hi = n, ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if ((long long)mid * mid <= n) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
};
class Solution {
int floorSqrt(int n) {
int lo = 0, hi = n, ans = 0;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if ((long)mid * mid <= n) {
ans = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return ans;
}
}
class Solution:
def floorSqrt(self, n):
lo, hi = 0, n
ans = 0
while lo <= hi:
mid = lo + (hi - lo) // 2
if mid * mid <= n:
ans = mid
lo = mid + 1
else:
hi = mid - 1
return ans
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐