Leetcode 1699 Solution

This article provides solution to leetcode question 1699 (number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers)

https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers

Solution

class Solution:
    def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
        def cal(nums, target):
            cnts = collections.defaultdict(int)
            for num in nums:
                cnts[num] += 1

            ans = 0
            for num in nums:
                cnts[num] -= 1

                if target % num != 0:
                    continue

                ans += cnts[target // num]

            return ans

        ans = 0
        for num1 in nums1:
            ans += cal(nums2, num1 * num1)
        for num2 in nums2:
            ans += cal(nums1, num2 * num2)
        return ans