Problem
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.length
and0 <= j < k < nums2.length
. - Type 2: Triplet (i, j, k) if
nums2[i]2 == nums1[j] * nums1[k]
where0 <= i < nums2.length
and0 <= j < k < nums1.length
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums1.length, nums2.length <= 1000
1 <= nums1[i], nums2[i] <= 10^5
Solution
Method 1 – Hash Map for Pair Products
Intuition
For each number in one array, count how many pairs in the other array multiply to its square. Use a hash map to count all pair products efficiently.
Approach
- For each number in nums1, count pairs in nums2 whose product equals its square. Do the same for nums2 and nums1.
- For each array, build a hash map of product counts for all pairs (j < k).
- For each number in the other array, add the count of pairs whose product equals its square.
- Sum both directions for the answer.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m^2 + n^2)
, where m and n are the lengths of nums1 and nums2. We count all pairs in each array. - 🧺 Space complexity:
O(m^2 + n^2)
, for storing all pair products in hash maps.