The problem is to implement the function int mySqrt(int x) that computes and returns the square root of x rounded down to the nearest integer. In other words, it returns the greatest integer q such that q^2 is less than or equal to x.
For example:
x = 4, Output: 2x = 8, Output: 2The input x is a non-negative integer, and we need to ensure the solution handles edge cases such as x = 0.
x be a negative number?
x is a non-negative integer.x?
x can be as large as the maximum value for an integer (2^31 - 1).A simple way to solve this problem is by using binary search:
left to 0 and right to x.mid such that mid * mid <= x.left and right based on the comparison of mid * mid with x.The binary search approach will ensure we have a time complexity of O(log x), which is efficient for handling up to the maximum possible value of x.
Here is the C++ implementation of the described strategy:
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0; // Handle the edge case where x is 0
int left = 1, right = x, ans = 0;
while (left <= right) {
int mid = left + (right - left) / 2;
if (mid <= x / mid) { // Avoiding overflow with mid*mid <= x
ans = mid;
left = mid + 1; // Try for a higher number
} else {
right = mid - 1; // Try for a lower number
}
}
return ans;
}
};
The time complexity of this solution is O(log x) due to the binary search mechanism. This ensures that for very large values of x (up to 2^31 - 1), the computation remains efficient. The space complexity is O(1) as we are using a constant amount of space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?