#367

Valid Perfect Square

Easy
MathBinary SearchBinary SearchMathematical Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Instead of checking every integer, we can use binary search to efficiently find the integer whose square might equal num. This reduces the number of checks significantly.

⚙️

Algorithm

6 steps
  1. 1Step 1: Initialize left to 1 and right to num.
  2. 2Step 2: While left is less than or equal to right, calculate mid as (left + right) / 2.
  3. 3Step 3: If mid * mid equals num, return true.
  4. 4Step 4: If mid * mid is less than num, move left to mid + 1.
  5. 5Step 5: If mid * mid is greater than num, move right to mid - 1.
  6. 6Step 6: If no perfect square is found, return false.
solution.py13 lines
1# Full working Python code
2
3def isPerfectSquare(num):
4    left, right = 1, num
5    while left <= right:
6        mid = (left + right) // 2
7        if mid * mid == num:
8            return True
9        elif mid * mid < num:
10            left = mid + 1
11        else:
12            right = mid - 1
13    return False

Complexity note: The time complexity is O(log n) because we are halving the search space with each iteration of the binary search. The space complexity is O(1) as we only use a constant amount of space.

  • 1Binary search significantly reduces the number of checks needed.
  • 2Understanding the properties of perfect squares helps in optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.