avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home 367-Valid Perfect Square
文章

367-Valid Perfect Square

Posted 2025-04-10
4~5 min read

[367-Valid Perfect Square]

🔗 LeetCode Link


Problem Description

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.

Constraints: 0 <= x <= 231 - 1


Idea

Since the array is sorted, binary search is the most efficient choice (O(log n)).


Logic

  1. Define your search range (0 - x)
  2. Use a loop (while (left <= right) or while (left < right))
  3. Calculate mid, check if square(mid) == x
  4. change to the boundary accordingly
  5. Use (long) mid * mid to prevent integer overflow in large input cases (e.g. x = 2147395599)

Code (Java - Closed Interval)

class Solution {
    public boolean isPerfectSquare(int num) {
        // set search range
        int left = 0;
        int right = num;

        while(left <= right){
            int mid = left + (right - left)/2; 

            // to avoid int overflow
            long square =(long) mid * mid;

            if (square > num){
                right = mid - 1;
            }
            else if(square < num){
                left = mid + 1;
            }
            else{
                // can find root
                return true;
            }
        }
        return false;
        
    }
}


Binary Search, Leetcode
Share

Further Reading

Apr 10, 2025

34 - Find First and Last Position of Element in Sorted Array

Apr 10, 2025

367-Valid Perfect Square

Apr 9, 2025

Leetcode-69 - Sqrt(x)

[69 - Sqrt(x)]🔗 LeetCode LinkProblem DescriptionGiven a non-negative integer x, return the square root of x rounded down to the nearest integer. The

OLDER

Leetcode-69 - Sqrt(x)

NEWER

34 - Find First and Last Position of Element in Sorted Array

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents