Number of Squareful Arrays - Problem
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].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,17,8]
›
Output:
2
💡 Note:
Two valid permutations: [1,8,17] (1+8=9=3², 8+17=25=5²) and [17,8,1] (17+8=25=5², 8+1=9=3²)
Example 2 — No Valid Permutations
$
Input:
nums = [2,2,2]
›
Output:
1
💡 Note:
Only one arrangement [2,2,2], and 2+2=4=2² for all adjacent pairs, so it's squareful
Example 3 — Empty Result
$
Input:
nums = [2,3,5]
›
Output:
0
💡 Note:
No two numbers sum to a perfect square: 2+3=5, 2+5=7, 3+5=8, none are perfect squares
Constraints
- 1 ≤ nums.length ≤ 12
- 0 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,17,8] - need to count squareful permutations
2
Check Adjacencies
Find which pairs sum to perfect squares
3
Count Valid
Count permutations with all adjacent pairs squareful
Key Takeaway
🎯 Key Insight: Model as a graph where edges connect numbers that sum to perfect squares, then use backtracking to count valid paths
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code