Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 <= 120 <= nums[i] <= 109Problem summary: 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].
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math · Dynamic Programming · Backtracking · Bit Manipulation
[1,17,8]
[2,2,2]
permutations-ii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #996: Number of Squareful Arrays
class Solution {
public int numSquarefulPerms(int[] nums) {
int n = nums.length;
int[][] f = new int[1 << n][n];
for (int j = 0; j < n; ++j) {
f[1 << j][j] = 1;
}
for (int i = 0; i < 1 << n; ++i) {
for (int j = 0; j < n; ++j) {
if ((i >> j & 1) == 1) {
for (int k = 0; k < n; ++k) {
if ((i >> k & 1) == 1 && k != j) {
int s = nums[j] + nums[k];
int t = (int) Math.sqrt(s);
if (t * t == s) {
f[i][j] += f[i ^ (1 << j)][k];
}
}
}
}
}
}
long ans = 0;
for (int j = 0; j < n; ++j) {
ans += f[(1 << n) - 1][j];
}
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
int[] g = new int[13];
g[0] = 1;
for (int i = 1; i < 13; ++i) {
g[i] = g[i - 1] * i;
}
for (int v : cnt.values()) {
ans /= g[v];
}
return (int) ans;
}
}
// Accepted solution for LeetCode #996: Number of Squareful Arrays
func numSquarefulPerms(nums []int) (ans int) {
n := len(nums)
f := make([][]int, 1<<n)
for i := range f {
f[i] = make([]int, n)
}
for j := range nums {
f[1<<j][j] = 1
}
for i := 0; i < 1<<n; i++ {
for j := 0; j < n; j++ {
if i>>j&1 == 1 {
for k := 0; k < n; k++ {
if i>>k&1 == 1 && k != j {
s := nums[j] + nums[k]
t := int(math.Sqrt(float64(s)))
if t*t == s {
f[i][j] += f[i^(1<<j)][k]
}
}
}
}
}
}
for j := 0; j < n; j++ {
ans += f[(1<<n)-1][j]
}
g := [13]int{1}
for i := 1; i < 13; i++ {
g[i] = g[i-1] * i
}
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
for _, v := range cnt {
ans /= g[v]
}
return
}
# Accepted solution for LeetCode #996: Number of Squareful Arrays
class Solution:
def numSquarefulPerms(self, nums: List[int]) -> int:
n = len(nums)
f = [[0] * n for _ in range(1 << n)]
for j in range(n):
f[1 << j][j] = 1
for i in range(1 << n):
for j in range(n):
if i >> j & 1:
for k in range(n):
if (i >> k & 1) and k != j:
s = nums[j] + nums[k]
t = int(sqrt(s))
if t * t == s:
f[i][j] += f[i ^ (1 << j)][k]
ans = sum(f[(1 << n) - 1][j] for j in range(n))
for v in Counter(nums).values():
ans //= factorial(v)
return ans
// Accepted solution for LeetCode #996: Number of Squareful Arrays
/**
* [0996] Number of Squareful Arrays
*
* 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] <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/number-of-squareful-arrays/
// discuss: https://leetcode.com/problems/number-of-squareful-arrays/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// credit: https://leetcode.com/problems/number-of-squareful-arrays/solutions/537277/rust-bfs-0ms-2-1m/
pub fn num_squareful_perms(nums: Vec<i32>) -> i32 {
let mut map = vec![vec![]; nums.len()];
let mut visited = std::collections::HashSet::new();
fn is_perfect_square(x: i32) -> bool {
((x as f64).sqrt() as i32).pow(2) == x
}
for i in 0..nums.len() {
for j in 0..nums.len() {
if i == j {
continue;
}
if is_perfect_square(nums[i] + nums[j]) {
map[i].push(j);
}
}
}
let mut queue = std::collections::VecDeque::new();
for i in 0..nums.len() {
queue.push_back(vec![i]);
}
let mut result = 0;
while let Some(sub) = queue.pop_front() {
if sub.len() == nums.len() {
result += 1;
continue;
}
let options = &map[sub[sub.len() - 1]];
for v in options {
if sub[0..].contains(&v) {
continue;
}
let mut next = sub[0..].to_vec();
next.push(*v);
let footprint =
format!("{:?}", next.iter().map(|x| nums[*x]).collect::<Vec<i32>>());
if !visited.contains(&footprint) {
visited.insert(footprint);
queue.push_back(next);
}
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0996_example_1() {
let nums = vec![1, 17, 8];
let result = 2;
assert_eq!(Solution::num_squareful_perms(nums), result);
}
#[test]
fn test_0996_example_2() {
let nums = vec![2, 2, 2];
let result = 1;
assert_eq!(Solution::num_squareful_perms(nums), result);
}
}
// Accepted solution for LeetCode #996: Number of Squareful Arrays
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #996: Number of Squareful Arrays
// class Solution {
// public int numSquarefulPerms(int[] nums) {
// int n = nums.length;
// int[][] f = new int[1 << n][n];
// for (int j = 0; j < n; ++j) {
// f[1 << j][j] = 1;
// }
// for (int i = 0; i < 1 << n; ++i) {
// for (int j = 0; j < n; ++j) {
// if ((i >> j & 1) == 1) {
// for (int k = 0; k < n; ++k) {
// if ((i >> k & 1) == 1 && k != j) {
// int s = nums[j] + nums[k];
// int t = (int) Math.sqrt(s);
// if (t * t == s) {
// f[i][j] += f[i ^ (1 << j)][k];
// }
// }
// }
// }
// }
// }
// long ans = 0;
// for (int j = 0; j < n; ++j) {
// ans += f[(1 << n) - 1][j];
// }
// Map<Integer, Integer> cnt = new HashMap<>();
// for (int x : nums) {
// cnt.merge(x, 1, Integer::sum);
// }
// int[] g = new int[13];
// g[0] = 1;
// for (int i = 1; i < 13; ++i) {
// g[i] = g[i - 1] * i;
// }
// for (int v : cnt.values()) {
// ans /= g[v];
// }
// return (int) ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.