π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 = 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.
Constraints:
$1 β€ n β€ 3 \times 10^4$
π― My Approach
Binary Search Initialization: We initialize two pointers
lo
(low) andhi
(high), wherelo = 0
andhi = n
.Binary Search Loop: We perform a binary search to find the integer square root of
n
. The middle elementmid
is computed as:mid = lo + (hi - lo) / 2
Check for Square: If
mid * 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 until
lo
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 and Auxiliary Space Complexity
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.
π 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