Valid Perfect Square - Problem

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

Input & Output

Example 1 — Perfect Square
$ Input: num = 16
Output: true
💡 Note: 16 is a perfect square because 4 * 4 = 16
Example 2 — Not Perfect Square
$ Input: num = 14
Output: false
💡 Note: 14 is not a perfect square. √14 ≈ 3.74, which is not an integer
Example 3 — Edge Case
$ Input: num = 1
Output: true
💡 Note: 1 is a perfect square because 1 * 1 = 1

Constraints

  • 1 ≤ num ≤ 231 - 1

Visualization

Tap to expand
Valid Perfect Square INPUT num = 16 Positive Integer Is 16 a perfect square? 4 x 4 = 16 units ALGORITHM STEPS Binary Search Approach 1 Initialize Bounds left=1, right=16 2 Calculate Mid mid = (left + right) / 2 3 Compare mid*mid with target num 4 Adjust Search Narrow left or right Iteration Example: L=1, R=16, mid=8 8*8=64 > 16, R=7 L=1, R=7, mid=4 4*4=16 == 16 OK! Return true FINAL RESULT true Perfect Square! 16 = 4 x 4 4 is an integer Verification sqrt(16) = 4 4 * 4 = 16 16 == 16 [OK] Found integer root! Key Insight: Binary Search efficiently finds if a perfect square root exists in O(log n) time. Instead of checking all numbers from 1 to n, we halve the search space each iteration. If mid*mid equals num, we found the root. Otherwise, adjust bounds based on comparison. TutorialsPoint - Valid Perfect Square | Binary Search Approach
Asked in
Facebook 15 LinkedIn 12
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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