13. Square Root of a Number
The problem can be found at the following link: Question Link
Problem Description
Given an integer n, find the square root of n. If n is not a perfect square, return the floor value of the square root.
Example:
Input:
n = 5Output:
2Explanation: Since 5 is not a perfect square, the floor of the square root of 5 is 2.
My Approach
Initial Check:
If
nis 0 or 1, returnnimmediately as the square root of 0 is 0 and the square root of 1 is 1.
Binary Search:
Initialize
startto 1 andendton. This range will be used to perform a binary search to find the square root.While
startis less than or equal toend, calculate the midpointmidand square it.If the square of
midequalsn, returnmidasnis a perfect square.If the square of
midis less thann, storemidas the current best guess for the square root and move thestartpointer tomid + 1.If the square of
midis greater thann, move theendpointer tomid - 1.When the loop ends, return the last best guess stored in
ans, which represents the floor value of the square root.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(log n), as we are performing a binary search over the range of possible square roots.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables.
Code (C++)
Code (Java)
Code (Python)
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