How to check if a number is a perfect square using binary search in Java.

👉 LeetCode 367: Valid Perfect Square. Binary search problem - this time to check if a number is a perfect square without using any built-in square root function. 👇 Here’s my implementation: class Solution {   public boolean isPerfectSquare(int num) {     if(num == 1){       return true;     }     int left = 1, right = num/2;     while(left<=right){       int mid = left + (right-left)/2;       if(mid == num/mid && num%mid == 0){         return true;       }else if(mid < num/mid){         left = mid + 1;       }else{         right = mid - 1;       }     }     return false;         } } 👉 Step-by-step logic: 1. Handle the edge case when num is 1. 2. Use binary search between 1 and num/2. 3. Calculate mid, then check if mid * mid == num. .To avoid overflow, the code uses num/mid instead of mid * mid. 4. If it matches perfectly and num % mid == 0, return true. 5. Adjust search boundaries accordingly until you find it or exhaust all options. 👉 Time Complexity:O(log n) — binary search halves the range each time. 👉 Space Complexity:O(1) — only a few integer variables are used. #LeetCode #Java #ProblemSolving #BinarySearch #Coding

To view or add a comment, sign in

Explore content categories