|
| 1 | +/** |
| 2 | + * 1577. Number of Ways Where Square of Number Is Equal to Product of Two Numbers |
| 3 | + * https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and |
| 7 | + * type 2) under the following rules: |
| 8 | + * - Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length |
| 9 | + * and 0 <= j < k < nums2.length. |
| 10 | + * - Type 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length |
| 11 | + * and 0 <= j < k < nums1.length. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number[]} nums1 |
| 16 | + * @param {number[]} nums2 |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var numTriplets = function(nums1, nums2) { |
| 20 | + return countTriplets(nums1, nums2) + countTriplets(nums2, nums1); |
| 21 | + |
| 22 | + function countTriplets(arr1, arr2) { |
| 23 | + const productMap = new Map(); |
| 24 | + let count = 0; |
| 25 | + |
| 26 | + for (let i = 0; i < arr2.length; i++) { |
| 27 | + for (let j = i + 1; j < arr2.length; j++) { |
| 28 | + const product = BigInt(arr2[i]) * BigInt(arr2[j]); |
| 29 | + productMap.set(product, (productMap.get(product) || 0) + 1); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + for (const num of arr1) { |
| 34 | + const square = BigInt(num) * BigInt(num); |
| 35 | + if (productMap.has(square)) { |
| 36 | + count += productMap.get(square); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return count; |
| 41 | + } |
| 42 | +}; |
0 commit comments