Math Fundamentals18 sections · 814 units
Open in Course

Perfect Square - Implementation

Binary search solution

Here's the binary search approach:


function isPerfectSquare(num)
    if num = 1 then
        return true
    left := 1
    right := num
    while left  right
        mid := left + (right - left) / 2
        square := mid * mid
        if square = num then
            return true
        else if square < num then
            left := mid + 1
        else
            right := mid - 1
    return false

Time: O(lognum)O(\log num). Space: O(1)O(1). You avoid overflow by using mid=left+(rightleft)/2mid = left + (right - left) / 2 instead of (left+right)/2(left + right) / 2.