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]

To solve this, we will follow these steps −

  • res := 0

  • Define a function util() . This will take i

  • if i + 1 is same as size of nums , then

    • res := res + 1

    • return

  • visited := a new empty set

  • for j in range i + 1 to size of nums, do

    • s := nums[i] + nums[j]

    • if s is not visited and (square root of s)^2 is s, then

      • mark s as visited

      • swap nums[i + 1] and nums[j]

      • util(i + 1)

      • swap nums[i + 1] and nums[j]

  • From the main method do the following −

  • visited := a new set

  • for i in range 0 to size of nums, do

    • swap nums[i] and nums[0]

    • if nums[0] is not visited, then

      • util(0)

    • mark nums[0] as visited

    • swap nums[i] and nums[0]

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

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
ob = Solution()
nums = [2, 9, 7]
print(ob.solve(nums))

Input

[2, 9, 7]

Output

2

Updated on: 26-Dec-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements