π4. Square Root π§
The problem can be found at the following link: Problem Link
π‘ Problem Description
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.
π Example Walkthrough
Input:
n = 4Output:
2Explanation: Since 4 is a perfect square, its square root is 2.
Input:
n = 11Output:
3Explanation: Since 11 is not a perfect square, the floor of the square root of 11 is 3.
Input:
n = 1Output:
1Explanation: Since 1 is a perfect square, the square root is 1.
Constraints:
$1 β€ n β€ 3 \times 10^4$
π― My Approach
Binary Search Initialization: We initialize two pointers
lo(low) andhi(high), wherelo = 0andhi = n.Binary Search Loop: We perform a binary search to find the integer square root of
n. The middle elementmidis computed as:mid = lo + (hi - lo) / 2Check for Square: If
mid * mid <= n, we update the result tomid(since it is a valid candidate for the square root) and shift thelopointer tomid + 1. Otherwise, we move thehipointer tomid - 1.End Condition: The loop continues until
loexceedshi, and at the end of the search, the value stored inanswill be the largest integer whose square is less than or equal ton.
π Time and Auxiliary Space Complexity
Time Complexity: O(log n), where
nis 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.
π Solution Code
Code (C)
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;
}Code (C++)
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;
}
};Code (Java)
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;
}
}Code (Python)
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π’ Contribution and Support
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! β
πVisitor Count
Last updated