Check if product of array containing prime numbers is a perfect square in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums with all prime numbers. We have to check whether the product of all numbers present in nums is a perfect square or not.

So, if the input is like nums = [3,3,7,7], then the output will be True as product of all elements in nums is 441 which is a perfect square as 21^2 = 441.

To solve this, we will follow these steps −

  • m := a map containing all elements in nums and their frequencies
  • for each key in nums, do
    • if m[key] is odd, then
      • return False
  • return True


Let us see the following implementation to get better understanding −

 Live Demo

from collections import defaultdict
def solve(nums) :
   m = defaultdict(int)
   for key in nums :
      m[key] += 1
   for key in nums :
      if m[key] % 2 == 1 :
         return False
   return True
nums = [3,3,7,7]




Published on 19-Jan-2021 09:58:56