Solving Leetcode Interviews in Seconds with AI: Number of Squareful Arrays
Introduction
In this blog post, we will explore how to solve the LeetCode problem "996" 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
An array is squareful if the sum of every pair of adjacent elements is a perfect square. Given an integer array nums, return the number of permutations of nums that are squareful. Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i]. Example 1: Input: nums = [1,17,8] Output: 2 Explanation: [1,8,17] and [17,8,1] are the valid permutations. Example 2: Input: nums = [2,2,2] Output: 1 Constraints: 1 <= nums.length <= 12 0 <= nums[i] <= 109
Explanation
Here's a breakdown of the solution:
- Build Adjacency Graph: Construct a graph where nodes are the numbers in the input array
nums. An edge exists between two numbers if their sum is a perfect square. This graph represents the possible adjacencies in squareful permutations. - Count Permutations with Backtracking: Use a recursive backtracking approach to explore all possible permutations. Keep track of which numbers have been used in the current permutation using a
visitedarray. Handle Duplicates: Use a
Counterto count the occurrences of each number in the input array. This allows us to correctly account for permutations that are identical due to duplicate numbers.Time Complexity: O(n!), where n is the length of
numsin the worst case, as it explores all possible permutations. However, the graph structure and visited array pruning significantly reduce the actual runtime. Space Complexity: O(n), primarily due to the adjacency graph,visitedarray, and recursion depth.
Code
from collections import Counter
import math
def numSquarefulPerms(nums):
n = len(nums)
count = Counter(nums)
graph = {num: [] for num in count}
for x in count:
for y in count:
if is_square(x + y):
graph[x].append(y)
def backtrack(curr, remaining):
if not remaining:
return 1
ans = 0
visited = set() # Prevent starting with the same number multiple times at each level
for neighbor in list(count.keys()):
if count[neighbor] > 0 and neighbor not in visited:
count[neighbor] -= 1
visited.add(neighbor)
ans += backtrack(neighbor, remaining - 1)
count[neighbor] += 1 # Backtrack : restore the count
return ans
def is_square(n):
if n < 0:
return False
root = int(math.sqrt(n))
return root * root == n
return backtrack(None, n)