↓Skip to main content
  1. LeetCode/

LeetCode 367: Valid Perfect Square

·1 min· ·
LeetCode Easy Math Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted ×2

Approach
#

The built-in square root is off limits. mid² grows with mid, so binary search [1, num] (Binary Search Template 4): equal means a perfect square, too small goes right, too large goes left.

My Attempts
#

Both submissions passed; the November one actually returned nothing (None) when not found, which LeetCode happened to treat as False.

Solution
#

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        l, r = 1, num
        while l <= r:
            mid = (l + r) // 2
            sq = mid * mid
            if sq == num:
                return True
            if sq < num:
                l = mid + 1
            else:
                r = mid - 1
        return False

Complexity
#

Time O(log num), space O(1).

Mistakes to Avoid
#

  • Return False when not found, not nothing (None).

Interview Explanation
#

Squares increase monotonically, so I binary search 1 to num; a square equal to num means yes. Time O(log num).

Related

LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer
LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 412: Fizz Buzz
·1 min
LeetCode Easy Math String Simulation
LeetCode 412 note: check multiples of 15 first, then 5 and 3; multiples need %, not //
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive