Valid Perfect Square - Problem

Imagine you're given a mysterious number and need to determine if it's a perfect square without using any built-in square root functions - like a mathematical detective!

A perfect square is a number that can be expressed as the product of an integer with itself. For example:

  • 16 is a perfect square because 4 × 4 = 16
  • 25 is a perfect square because 5 × 5 = 25
  • 14 is NOT a perfect square because no integer multiplied by itself equals 14

Your task: Given a positive integer num, return true if it's a perfect square, false otherwise.

The Challenge: You cannot use any built-in library functions like sqrt() or Math.sqrt(). You must implement your own logic to solve this mathematical puzzle!

Input & Output

example_1.py — Perfect Square
$ Input: num = 16
Output: true
💡 Note: 16 is a perfect square because 4 × 4 = 16. The square root of 16 is exactly 4, which is an integer.
example_2.py — Not Perfect Square
$ Input: num = 14
Output: false
💡 Note: 14 is not a perfect square. The square root of 14 is approximately 3.74, which is not an integer. No integer multiplied by itself equals 14.
example_3.py — Edge Case
$ Input: num = 1
Output: true
💡 Note: 1 is a perfect square because 1 × 1 = 1. This is the smallest perfect square.

Constraints

  • 1 ≤ num ≤ 231 - 1
  • Cannot use built-in sqrt functions
  • Must handle integer overflow properly in calculations

Visualization

Tap to expand
Perfect Square Detection: Binary Search JourneyTarget: 16 (Looking for √16)Search Range: [1, 16]1816LEFTMID: 8²=64 > 16RIGHT148LEFTMID: 4²=16 ✓RIGHTFOUND!4² = 16Binary search finds the answer in just 2 steps instead of checking 4 numbers sequentially!
Understanding the Visualization
1
Set the Playing Field
Establish search boundaries from 1 to the target number
2
Make Smart Guesses
Use binary search to guess the middle value and check its square
3
Eliminate Impossibilities
If guess² is too big, eliminate the upper half; if too small, eliminate lower half
4
Find the Answer
Continue until you find exact match or determine no perfect square exists
Key Takeaway
🎯 Key Insight: Binary search transforms a linear O(√n) problem into a logarithmic O(log n) solution by intelligently eliminating half the search space in each iteration
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
34.5K Views
Medium Frequency
~15 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen