Problem of the day
You are given an Array/List Arr of non-negative integers. Your task is to return the number of Squareful permutations of the array.
An array is called Squareful if the sum of every pair of adjacent elements is a perfect square.
Example
ARR[1,3,6] is a Squareful array as 1+3=4 i.e. 2^2 , 3+6=9 i.e. 3^2.
Two permutations ARR1 and ARR2, are different from each other if there exit an index i such that ARR1[i] != ARR2[i].
Example:
[1,6,3] and [6,1,3] are different permutations.
The first line contains an integer ‘N’, representing the array’s size.
The second contains 'N' space-separated integers, denoting the elements of the array.
Output format
For each test case, return an integer denoting the number of Squareful Permutation of array ARR.
Note:
You don’t need to print anything or take input; it already has been taken care of. Just implement the function.
1 <= N <= 12
0 <= ARR[i] <= 10^4 , where 0 <= i < N
Time limit: 1 sec
3
1 24 3
2
Different permutations of [1, 24, 3] are - [1, 24, 3] , [1, 3, 24] , [24, 1, 3] , [24, 3, 1] , [3, 1, 24] , [3, 24, 1].
Out of which [24, 1, 3] (24 + 1 = 25, 1 + 3 = 4) and [3, 1, 24] (3 + 1 = 4, 1 + 14 = 25) are Squareful.
4
1 1 1 1
0
Check all permutations.
In this approach, we will check all the permutations of the array. And for each permutation in array ‘ARR’, check if ARR[i]+ARR[i+1] is a perfect square. If it is a perfect square, then increase the answer by 1. Return answer.
Algorithm:-
O(N! * N) where ‘N’ is the size of the array.
For the array of size ‘N’, there are N! possible permutations and we are checking all permutations for which we have to iterate through the array of size ‘N’, and for checking square root we use sqrt function. So our time complexity is N! * N = O(N! * N)
O(1),
No extra space is used.