File: valid-perfect-square/solution.py

Date: 2026-06-06

Time: 19:40

valid-perfect-square/solution.py

Purpose

This file solves LeetCode 367 — Valid Perfect Square. It determines whether a given positive integer is a perfect square without using a built-in square root function. It's one of ~500 problem solutions in the leetcode-implementations repo, each following the same directory convention (problem-slug/solution.py).

Key Components

isperfectsquare(num: int) -> bool — The sole public function. Takes a positive integer in [1, 2^31 - 1] and returns whether some integer m exists such that m * m == num.

Patterns

Binary search on the answer space. Rather than iterating candidates linearly or using Newton's method, the solution binary-searches the range [1, num] for a value whose square equals num. This is the canonical "binary search on value" pattern — the search space is monotonic (squaring is strictly increasing for positive integers), so standard binary search applies directly.

The midpoint calculation mid = lo + (hi - lo) // 2 avoids integer overflow in languages with fixed-width integers. In Python this is technically unnecessary (arbitrary-precision ints), but it's a good habit that makes the solution portable.

Dependencies

Imports: None — pure computation with no library dependencies.

Imported by: The "Imported By" list in the prompt is misleading — those are unrelated test files across the entire repo that happen to share a common test harness import pattern. The actual consumer is valid-perfect-square/testsolution.py, which imports isperfect_square to test it.

Flow

1. Initialize lo = 1, hi = num.

2. While the search window is non-empty (lo <= hi):

3. If the loop exits without a match, num has no integer square root — return False.

Time complexity: O(log n). Space complexity: O(1).

Invariants

Error Handling

None. The function is a pure predicate with no failure modes under valid input. No exceptions are raised or caught.

Topics to Explore

Beliefs