646. Square Neighbours
An arrangement of numbers in a row is tidy if the sum of every two neighbouring numbers is a perfect square (such as 1, 4, 9, 16, 25 and so on). Given the array nums, count the number of different tidy arrangements of all its numbers.
Two arrangements are different if at some position they hold different values; swapping two equal numbers does not create a new arrangement. A single number has no neighbours, so an array of length 1 has exactly one tidy arrangement.
Example 1
- Input:
- nums = [1,3,6]
- Output:
- 2
- Explanation:
The sums 1+3 = 4 and 3+6 = 9 are squares, but 1+6 = 7 is not. Only the arrangements
[1, 3, 6]and[6, 3, 1]work.
Example 2
- Input:
- nums = [8,8,8]
- Output:
- 1
- Explanation:
All arrangements are the same array, and 8 + 8 = 16 is a square, so the answer is 1.
Example 3
- Input:
- nums = [1,2,3]
- Output:
- 0
- Explanation:
1+2 = 3 and 2+3 = 5 are not squares and 1+3 = 4 is the only square sum, but a row of three needs two good neighbour pairs. No tidy arrangement exists.
Constraints
- 1 ≤
nums.length≤ 12 - 0 ≤
nums[i]≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 800 msC++ 200 msJava 400 msJavaScript 400 msTypeScript 400 ms
Expected complexity
- Time
- O(states * k) where states <= (counts + 1) product * k
- Space
- O(states)