Solving Leetcode Interviews in Seconds with AI: Valid Perfect Square
Introduction
In this blog post, we will explore how to solve the LeetCode problem "367" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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. Example 1: Input: num = 16 Output: true Explanation: We return true because 4 4 = 16 and 4 is an integer. Example 2: Input: num = 14 Output: false Explanation: We return false because 3.742 3.742 = 14 and 3.742 is not an integer. Constraints: 1 <= num <= 231 - 1
Explanation
Here's the solution to determine if a number is a perfect square without using built-in square root functions:
- Binary Search: Employ binary search on the range
[1, num]to efficiently find the potential square root. - Midpoint Check: In each iteration, calculate the square of the midpoint. If the square equals
num, returntrue. Adjust Search Range: If the square is less than
num, narrow the search to the upper half. Otherwise, narrow it to the lower half. If the binary search completes without finding an exact square, returnfalse.Runtime Complexity: O(log n), where n is the input number
num. Storage Complexity: O(1).
Code
def isPerfectSquare(num: int) -> bool:
"""
Given a positive integer num, return true if num is a perfect square or false otherwise.
You must not use any built-in library function, such as sqrt.
Example 1:
Input: num = 16
Output: true
Explanation: We return true because 4 * 4 = 16 and 4 is an integer.
Example 2:
Input: num = 14
Output: false
Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.
Constraints:
1 <= num <= 231 - 1
"""
left, right = 1, num
while left <= right:
mid = left + (right - left) // 2
square = mid * mid
if square == num:
return True
elif square < num:
left = mid + 1
else:
right = mid - 1
return False