#996
Number of Squareful Arrays
HardArrayHash TableMathDynamic ProgrammingBacktrackingBit ManipulationBitmaskBacktrackingFrequency Map
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n!) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n!)Space O(n)
The optimal solution uses backtracking with a frequency map to avoid generating duplicate permutations. It only checks valid adjacent pairs during the construction of the permutation, making it more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map of the numbers in the array.
- 2Step 2: Use backtracking to build permutations, ensuring each adjacent pair sums to a perfect square.
- 3Step 3: Count valid permutations as they are formed.
solution.py27 lines
1import math
2from collections import Counter
3
4
5def is_perfect_square(x):
6 return int(math.sqrt(x))**2 == x
7
8
9def backtrack(nums, path, count, freq):
10 if len(path) == len(nums):
11 count[0] += 1
12 return
13 for num in freq:
14 if freq[num] > 0:
15 if len(path) == 0 or is_perfect_square(path[-1] + num):
16 path.append(num)
17 freq[num] -= 1
18 backtrack(nums, path, count, freq)
19 path.pop()
20 freq[num] += 1
21
22
23def numSquarefulPerms(nums):
24 freq = Counter(nums)
25 count = [0]
26 backtrack(nums, [], count, freq)
27 return count[0]ℹ
Complexity note: The time complexity remains O(n!) due to the nature of permutations, but we avoid generating duplicates, making it more efficient in practice. The space complexity is O(n) for the recursion stack and frequency map.
- 1Understanding perfect squares is crucial for this problem.
- 2Using a frequency map helps in managing duplicates efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.