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
Number of Squareful Arrays INPUT Array: nums 1 17 8 [0] [1] [2] Perfect Squares: 1, 4, 9, 16, 25, 36... Adjacent Pair Sums: 1+17=18 1+8=9 OK 17+8=25 OK Squareful Graph: 1 8 17 ALGORITHM STEPS 1 Build Graph Connect pairs with perfect square sums 2 DFS/Backtracking Try each starting node Traverse valid paths 3 Handle Duplicates Sort array, skip same elements at same level 4 Count Valid Perms Count paths using all elements once DFS Exploration: Start [1,..] [8,..] [17,..] FINAL RESULT Valid Squareful Perms: Permutation 1: 1 8 17 OK 9 25 Permutation 2: 17 8 1 OK 25 9 Output: 2 Two valid squareful permutations found! Key Insight: Model the problem as a graph where nodes are array elements and edges connect pairs with perfect square sums. A valid permutation is a Hamiltonian path in this graph. Use DFS with backtracking to count all such paths. Time: O(N!), Space: O(N) TutorialsPoint - Number of Squareful Arrays | Optimal Solution (Graph + DFS Backtracking)
Asked in
Google 25 Facebook 20 Amazon 15
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen