Skip to main content
Back to problems
#367
Easy Algorithms

Valid perfect square

Math Binary Search
44.7% acceptance
Jan 12, 2026
4648
338
Given a positive integer num, return true if num is a perfect square or false otherwise. A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself. You must not use any built-in library function, such as sqrt.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn is_perfect_square(num: i32) -> bool {
    if num < 1 {
      return false;
    }
    
    let mut left = 1i64;
    let mut right = num as i64;
    
    while left <= right {
      let mid = left + (right - left) / 2;
      let square = mid * mid;
      
      if square == num as i64 {
        return true;
      } else if square < num as i64 {
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }
    
    false
  }
}