Given a non-negative number find the square root of a number using the binary search approach.
Input: x = 16 Output: 4 Explanation: The square root of 16 is 4. Input: x = 5 Output: 2 Explanation: The square root of 5 lies in between 2 and 3 so floor of the square root is 2.
- Check the square of every element till n and store the answer till the square is smaller or equal to the n
Efficient Approach (Binary Search): Binary Search used Divide and Conquer approach that makes the complexity is O(logn).
- Initialize left=0 and right =n
- Calculate mid=left+(right-left)/2
- If mid*mid is equal to the number return the mid.
- If mid*mid is less than the number store the mid in ans since this can possibly be the answer and increase left=mid+1 and now check in the right half.
- If mid*mid is more than the number and decrease the right=mid-1 since the expected value is lesser therefore we will now look into the left half part or will be scanning the smaller values.
- Return the answer
Time Complexity: O(logn)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.