367. Valid Perfect Square (Leetcode || Easy || Java)

Palakkgoyal
1 min readOct 26, 2022

--

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Follow up: Do not use any built-in library function such as sqrt.

Example 1:

Input: num = 16
Output: true

Example 2:

Input: num = 14
Output: false

Constraints:

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

SOLUTION:

class Solution {
public boolean isPerfectSquare(int num) {
if(num == 1){//if num is 1 return true
return true;
}

//determining the range for searching
int start = 1;
int end = num/2;

while(start <= end){//Applying binary search
int mid = start + (end — start)/2;

if((long)mid*mid == num){//if we get the number is square of some number, return true and we use long data type here because mid*mid can exceed the limited value of an integer
return true;
}
else if((long)mid*mid > num){
end = mid -1;
}else{
start = mid + 1;
}
}

return false;//if you don’t find root of the given number return false
}
}

TIME COMPLEXITY : O(log(n))

SPACE COMPLEXITY : O(1)

Thank you for reading. If you have any queries, please let me now int the comment section

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet