KatInterview

367. Valid Perfect Square

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of the problem is to determine if a given positive integer num is a perfect square without using any built-in library functions like sqrt. A perfect square is an integer that is the square of another integer (e.g., 16 = 4 * 4).

Solution

Valid Perfect Square in Python

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        # According to constraints, num >= 1.
        if num == 1:
            return True
        
        # Binary search for the integer square root.
        # The search space for the root is [1, num].
        left, right = 1, num
        
        while left <= right:
            # In Python, integers have arbitrary precision, so overflow is not an issue
            # for mid calculation or for the square.
            mid = (left + right) // 2
            
            square = mid * mid
            
            if square == num:
                return True # Found the exact integer square root.
            elif square < num:
                # The square root must be larger.
                left = mid + 1
            else: # square > num
                # The square root must be smaller.
                right = mid - 1
                
        # If the loop completes, no integer square root was found.
        return False

Valid Perfect Square in Java

class Solution {
    public boolean isPerfectSquare(int num) {
        // According to constraints, num >= 1.
        if (num == 1) {
            return true;
        }

        // Binary search for the integer square root.
        // The search space for the root is [1, num].
        int left = 1;
        int right = num;

        while (left <= right) {
            // Calculate mid. Use this formula to prevent overflow if left+right is large.
            int mid = left + (right - left) / 2;

            // Use long for the square to prevent overflow, as mid*mid can exceed Integer.MAX_VALUE.
            long square = (long) mid * mid;

            if (square == num) {
                return true; // Found the exact integer square root.
            } else if (square < num) {
                // The square root must be in the right half.
                left = mid + 1;
            } else { // square > num
                // The square root must be in the left half.
                right = mid - 1;
            }
        }

        // If the loop finishes, num is not a perfect square.
        return false;
    }
}

Valid Perfect Square in C++

class Solution {
public:
    bool isPerfectSquare(int num) {
        // According to constraints, num >= 1.
        if (num == 1) {
            return true;
        }
        
        // Binary search for the integer square root.
        // The search space for the root is [1, num].
        int left = 1;
        int right = num;
        
        while (left <= right) {
            // Calculate mid. This form prevents overflow if left + right is too large.
            int mid = left + (right - left) / 2;
            
            // To prevent overflow when calculating mid*mid, we cast mid to a 64-bit integer.
            // The square of mid can exceed the maximum value of a 32-bit integer.
            long long square = (long long)mid * mid;
            
            if (square == num) {
                return true; // Found the exact integer square root.
            } else if (square < num) {
                // The square root must be in the right half of the search space.
                left = mid + 1;
            } else { // square > num
                // The square root must be in the left half of the search space.
                right = mid - 1;
            }
        }
        
        // If the loop completes, no integer square root was found.
        return false;
    }
};

Valid Perfect Square in TypeScript

function isPerfectSquare(num: number): boolean {
    // According to constraints, num >= 1.
    if (num === 1) {
        return true;
    }

    // Binary search for the integer square root.
    // The search space is [1, num].
    let left = 1;
    let right = num;

    while (left <= right) {
        // Calculate mid. Use Math.floor to ensure it's an integer.
        const mid = Math.floor(left + (right - left) / 2);
        
        // In JS/TS, `number` is a 64-bit float. `mid * mid` can suffer precision loss
        // if it exceeds Number.MAX_SAFE_INTEGER. However, for a 32-bit `num` input,
        // the largest possible integer root is ~46340. `46340*46340` is well within
        // the safe integer limit. The `mid` value itself can be large initially, but
        // the comparisons will quickly narrow it down. The division approach is safer for
        // arbitrary large numbers but multiplication is fine here given constraints.

        const square = mid * mid;

        if (square === num) {
            return true; // Found the exact integer square root.
        } else if (square < num) {
            // The square root must be in the right half.
            left = mid + 1;
        } else { // square > num
            // The square root must be in the left half.
            right = mid - 1;
        }
    }

    // If the loop finishes, num is not a perfect square.
    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.