Check whether a positive integer is a perfect square without using sqrt

Quick Overview

Decide whether a positive integer up to 2^31 - 1 is the square of an integer without calling a square root function. The problem tests searching a sorted range of candidates, getting the loop boundaries right, and avoiding overflow when squaring large values.

Check whether a positive integer is a perfect square without using sqrt

Company: Sap

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a positive integer `num`, return `True` if `num` is a perfect square and `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`. ### Function Signature ```python def is_perfect_square(num: int) -> bool: ... ``` ### Constraints - `1 <= num <= 2^31 - 1` ### Examples ```text Input: num = 16 Output: True ``` `4 * 4 = 16`, so 16 is a perfect square. ```text Input: num = 14 Output: False ``` `3 * 3 = 9` and `4 * 4 = 16`, so no integer squares to 14. ```text Input: num = 1 Output: True ``` `1 * 1 = 1`, so the smallest allowed input is a perfect square.

Overview: Decide whether a positive integer up to 2^31 - 1 is the square of an integer without calling a square root function. The problem tests searching a sorted range of candidates, getting the loop boundaries right, and avoiding overflow when squaring large values.

Sap logo
Sap
Nov 25, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a positive integer num, return True if num is a perfect square and 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.

Function Signature

def is_perfect_square(num: int) -> bool:
    ...

Constraints

  • 1 <= num <= 2^31 - 1

Examples

Input: num = 16
Output: True

4 * 4 = 16, so 16 is a perfect square.

Input: num = 14
Output: False

3 * 3 = 9 and 4 * 4 = 16, so no integer squares to 14.

Input: num = 1
Output: True

1 * 1 = 1, so the smallest allowed input is a perfect square.