Tutorialspoint
Problem
Solution
Submissions

Valid Perfect Square

Certification: Basic Level Accuracy: 25% Submissions: 4 Points: 5

Write a Java program to determine if a given positive integer is a perfect square without using the Math.sqrt() function or any other built-in square root function. A perfect square is an integer that is the square of an integer. For example, 16 is a perfect square because it is 4^2.

Example 1
  • Input: num = 16
  • Output: true
  • Explanation:
    • Step 1: 16 is a perfect square because it is equal to 4^2.
    • Step 2: 4 * 4 = 16
    • Step 3: Therefore, 16 is a perfect square.
Example 2
  • Input: num = 14
  • Output: false
  • Explanation:
    • Step 1: 14 is not a perfect square.
    • Step 2: The closest perfect squares are 9 (3^2) and 16 (4^2).
    • Step 3: Since 14 falls between these two perfect squares, it is not a perfect square itself.
Constraints
  • 1 ≤ num ≤ 2^31 - 1
  • You are not allowed to use any built-in library function such as Math.sqrt()
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
NumberWalmartD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use binary search to find the square root of the number
  • Start with a search range from 1 to num/2
  • For each mid value, check if mid * mid equals the given number
  • If mid * mid is greater than the number, search in the left half
  • If mid * mid is less than the number, search in the right half

Steps to solve by this approach:

 Step 1: Handle the edge case where num < 2, as 0 and 1 are perfect squares.
 Step 2: Initialize the search range with left = 1 and right = num/2 (since the square root can't be greater than num/2 for num > 1).
 Step 3: Use binary search to find a potential square root.
 Step 4: For each mid value, calculate mid * mid and compare it with num.
 Step 5: If mid * mid equals num, return true as we found the square root.
 Step 6: If mid * mid > num, search in the left half; otherwise, search in the right half.
 Step 7: If we exit the loop without finding a square root, return false.

Submitted Code :