Number of Ways Where Square of Number Is Equal to Product of Two Numbers Problem
Description
LeetCode Problem 1577.
Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:
- Type 1: Triplet (i, j, k) if
nums1[i]^2 == nums2[j] * nums2[k]where0 <= i < nums1.lengthand0 <= j < k < nums2.length. - Type 2: Triplet (i, j, k) if
nums2[i]^2 == nums1[j] * nums1[k]where0 <= i < nums2.lengthand0 <= j < k < nums1.length.
Example 1:
Input: nums1 = [7,4], nums2 = [5,2,8,9]
Output: 1
Explanation: Type 1: (1, 1, 2), nums1[1]^2 = nums2[1] * nums2[2]. (4^2 = 2 * 8).
Example 2:
Input: nums1 = [1,1], nums2 = [1,1,1]
Output: 9
Explanation: All Triplets are valid, because 1^2 = 1 * 1.
Type 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]^2 = nums2[j] * nums2[k].
Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]^2 = nums1[j] * nums1[k].
Example 3:
Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]
Output: 2
Explanation: There are 2 valid triplets.
Type 1: (3,0,2). nums1[3]^2 = nums2[0] * nums2[2].
Type 2: (3,0,1). nums2[3]^2 = nums1[0] * nums1[1].
Constraints:
1 <= nums1.length, nums2.length <= 10001 <= nums1[i], nums2[i] <= 10^5
Solution
Approach: Count Pair Products in a Hash Map
The two types are the same problem with the arrays swapped, so solve one direction and add the other.
For type 1 we need, for every x in nums1, the number of pairs j < k in nums2 with nums2[j] * nums2[k] == x * x. Precompute the products of all pairs of nums2 in a hash map from product to how many pairs give it. Then each x is a single lookup of x * x. Duplicates take care of themselves: every pair of indices is counted once in the map, and every index i in nums1 does its own lookup.
Do the same with nums1's pair products and the squares of nums2, and add the two counts.
Values go up to 10^5, so squares and products go up to 10^10: use 64-bit keys in Java, C++ and Go. The final count fits in a 32-bit integer.
Complexity: O(m2 + n2) time and space for arrays of lengths m and n, from storing the pair products.
from collections import Counter
class Solution:
def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:
def pair_products(nums: List[int]) -> Counter:
"""How many pairs j < k give each product nums[j] * nums[k]."""
count = Counter()
for j in range(len(nums)):
for k in range(j + 1, len(nums)):
count[nums[j] * nums[k]] += 1
return count
def matches(squares: List[int], products: Counter) -> int:
return sum(products[x * x] for x in squares)
return matches(nums1, pair_products(nums2)) + matches(nums2, pair_products(nums1))