Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Square Root
Using Binary Search



Problem Statement

Given a non-negative integer x, your task is to find its integer square root. The integer square root of x is the greatest integer r such that r * r ≤ x.

You must solve this problem without using any built-in square root functions. If x is negative, return -1 (square root of negative numbers is not defined in real numbers).

Examples

Input (x)OutputDescription
00Square root of 0 is 0
11Square root of 1 is 1
42Perfect square: 2 * 2 = 4
1033 * 3 = 9, 4 * 4 = 16 > 10. So answer is 3
10010Perfect square: 10 * 10 = 100
9999 * 9 = 81, 10 * 10 = 100 > 99. So answer is 9
10000001000Large number, 1000 * 1000 = 1000000
-25-1Negative input: square root not defined
-1Empty input or undefined: treated as invalid

Solution

To find the integer square root of a number x, we aim to identify the largest number whose square is less than or equal to x. Instead of testing each number from 1 up to x, which would be slow for large values, we use binary search for efficiency.

Understanding the Problem

The square root of a number x is a number r such that r * r ≤ x and (r + 1) * (r + 1) > x. We want this integer value of r.

Different Input Scenarios

  • Case 1 – Perfect Square: If x is a perfect square like 25 or 100, then the square root is exact. For example, 5 * 5 = 25, so the answer is 5.
  • Case 2 – Not a Perfect Square: For values like 10 or 99, the square root won’t be exact. We return the floor of the real square root. For 10, the real root is ~3.16, but we return 3.
  • Case 3 – Very Large Input: The binary search method still works efficiently even for inputs like 1,000,000. The loop only runs about log₂(x) times.
  • Case 4 – Small Numbers (0 or 1): These are trivial cases. The square root of 0 is 0, and the square root of 1 is 1.
  • Case 5 – Negative Numbers: Since we’re dealing with real numbers only, there’s no square root defined for negatives. We return -1 for input like -25.
  • Case 6 – Empty or Invalid Input: If the input is empty or not a number, we treat it as invalid and return -1 to indicate the error.

How Binary Search Helps

We use binary search to guess a number mid between 0 and x and check if mid * mid is equal to, less than, or greater than x. Based on that, we move the low and high pointers and gradually narrow down the search range. We also store the last value of mid that gives mid * mid ≤ x — this becomes our final answer.

This approach is very efficient and gives us the result in O(log x) time without needing any built-in math functions.

Visualization

Algorithm Steps

  1. Set low = 0 and high = x.
  2. Initialize ans = -1 to keep track of closest answer.
  3. While low ≤ high, do:
  4. → Find mid = (low + high) / 2.
  5. → If mid * mid == x, return mid.
  6. → If mid * mid < x, update ans = mid, and move low = mid + 1.
  7. → Else, move high = mid - 1.
  8. Return ans.

Code

Java
Python
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
public class SqrtBinarySearch {
  public static int sqrt(int x) {
    if (x == 0 || x == 1) return x;

    int start = 0, end = x, ans = -1;
    while (start <= end) {
      int mid = start + (end - start) / 2;
      long square = (long) mid * mid;

      if (square == x)
        return mid;
      else if (square < x) {
        ans = mid;          // Store potential answer
        start = mid + 1;    // Look right for a closer higher sqrt
      } else {
        end = mid - 1;      // Move left to reduce square
      }
    }
    return ans;
  }

  public static void main(String[] args) {
    int x = 15;
    System.out.println("Square root of " + x + " is: " + sqrt(x));
  }
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)If the square root is found in the first mid calculation.
Average CaseO(log x)Binary search narrows down the possible square root range in logarithmic time.
Average CaseO(log x)Search continues halving the range until low > high.

Space Complexity

O(1)

Explanation: No additional space is used; only constant variables are needed.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M