Program to count number of permutations where sum of adjacent pairs are perfect square in Python

Suppose we have a list of numbers called nums. We have to find the number of permutations of nums such that sum of every pair of adjacent values is a perfect square. Two permutations A and B are unique when there is some index i where A[i] is not same as B[i].

So, if the input is like nums = [2, 9, 7], then the output will be 2, as we have [2, 7, 9] and [9, 7, 2]. In both cases: 2+7=9 (perfect square), 7+9=16 (perfect square), and 9+7=16 (perfect square), 7+2=9 (perfect square).

Algorithm

To solve this problem, we will use backtracking with the following approach ?

  • For each starting element, try all possible next elements that form a perfect square sum

  • Use recursion to build valid permutations step by step

  • Avoid duplicate permutations by tracking visited starting elements

  • Check if sum of two numbers is a perfect square using square root validation

Implementation

from math import sqrt

class Solution:
    def solve(self, nums):
        self.res = 0
        
        def util(i):
            if i + 1 == len(nums):
                self.res += 1
                return
            
            visited = set()
            for j in range(i + 1, len(nums)):
                s = nums[i] + nums[j]
                if s not in visited and int(sqrt(s)) ** 2 == s:
                    visited.add(s)
                    nums[i + 1], nums[j] = nums[j], nums[i + 1]
                    util(i + 1)
                    nums[i + 1], nums[j] = nums[j], nums[i + 1]
        
        visited = set()
        for i in range(len(nums)):
            nums[i], nums[0] = nums[0], nums[i]
            if nums[0] not in visited:
                util(0)
            visited.add(nums[0])
            nums[i], nums[0] = nums[0], nums[i]
        
        return self.res

# Test the solution
ob = Solution()
nums = [2, 9, 7]
result = ob.solve(nums)
print(f"Number of valid permutations: {result}")
Number of valid permutations: 2

How It Works

The algorithm works in two main phases ?

  1. Starting Element Selection: Try each number as the first element of the permutation

  2. Recursive Building: For each position, find all valid next elements whose sum with current element is a perfect square

The key insight is using backtracking to swap elements and explore all possibilities while avoiding duplicate work by tracking visited sums.

Example with Different Input

# Test with a different set of numbers
ob = Solution()
nums = [1, 15, 8]
result = ob.solve(nums)
print(f"Input: {nums}")
print(f"Valid permutations: {result}")

# Let's verify: 1+15=16 (4²), 15+1=16 (4²), 1+8=9 (3²), 8+1=9 (3²)
# But 15+8=23 (not a perfect square)
Input: [1, 15, 8]
Valid permutations: 2

Perfect Square Verification

The condition int(sqrt(s)) ** 2 == s efficiently checks if a number is a perfect square by ?

  • Taking the square root and converting to integer

  • Squaring the result and comparing with original number

  • This handles floating-point precision issues

Conclusion

This backtracking solution efficiently counts permutations where adjacent pairs sum to perfect squares. The algorithm uses swapping and recursion to explore all possibilities while avoiding duplicates through visited sets.

Updated on: 2026-03-25T14:00:08+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements