[Javascript] Two Approaches - Hashmap & Two Pointers
Solution 1: Hashmap\n\nThis approach is similar to the two sum problem.\nWe use a hashmap to keep track of the frequencies of past numbers.\nCount the number of
**Solution 1: Hashmap**\n\nThis approach is similar to the two sum problem.\nWe use a hashmap to keep track of the frequencies of past numbers.\nCount the number of `target / nums2[j]` in the hashmap.\n\n`n = length of nums1`, `m = length of nums2`\nTime Complexity: `O(nm)` 498ms\nSpace Complexity: `O(n + m)` 48.3MB\n```\nvar numTriplets = function(nums1, nums2) {\n  return getTriplets(nums1, nums2) + getTriplets(nums2, nums1);\n  \n  function getTriplets(nums1, nums2) {\n    let ans = 0;\n    for (let i = 0; i < nums1.length; i++) {\n      let target = nums1[i] * nums1[i], map = new Map();\n      for (let j = 0; j < nums2.length; j++) {\n        ans += map.get(target / nums2[j]) || 0;\n        map.set(nums2[j], (map.get(nums2[j]) || 0) + 1);\n      }\n    }\n    return ans;\n  }\n};\n```\n\n\n**Solution 2: Three Pointers**\n\n1. Sort both arrays. This is so that we can use two pointers to calculate the pairs.\n2. For each `nums1[i] `\n  Use two pointers (`start = 0`, `end = n - 1`) in `nums2`\n  Count the number of pairs where `nums2[j] * nums2[k] === nums1[i] * nums1[i]`\n  There are two special cases to consider:\n\n    Case 1. `nums2[j] !== nums2[k]`.\n      An array like `[1,1,3,3]`. \n      Count the number of repeated `nums2[j]` and repeated `nums2[k]`.\n      Multiply the two counts together to get the number of combinations.\n\n    Case 2. `[nums2[j], ..., nums2[k]]` are all equal\n      e.g: `[1,1,1,1,1]`\n      For each `nums2[j]`, we can pair it with any number on the right.\n      For the above example this would be: `4 + 3 + 2 + 1`\n      Use the formula `(n-1)*n/2 `to calculate the sum of `1 + 2 + 3 + ... + n-1`\n\nTime Complexity: `O(nm + n log(n) + m log(m))` 153ms\nSpace Complexity: `O(log(n) + log(m))` (space for sorting) 43.1MB\n```\nvar numTriplets = function(nums1, nums2) {\n  nums1.sort((a, b) => a - b);\n  nums2.sort((a, b) => a - b);\n  return calc(nums1, nums2) + calc(nums2, nums1);\n  \n  function calc(nums1, nums2) {\n    let ans = 0;\n    for (let i = 0; i < nums1.length; i++) {\n      let target = nums1[i] * nums1[i];\n      let j = 0, k = nums2.length - 1;\n      while (j < k) {\n        if (nums2[j] * nums2[k] === target) {\n          if (nums2[j] === nums2[k]) { // case 2: [nums2[j], ..., nums2[k]] are all equal\n            ans += (k - j) * (k - j + 1) / 2;\n            j = k;\n          } else { // case 1: nums2[j] !== nums2[k]\n            let left = j, right = k;\n            while (j < k && nums2[j] === nums2[left]) j++;\n            while (k >= 0 && nums2[k] === nums2[right]) k--;\n            ans += (j - left) * (right - k);\n          }\n        }\n        else if (nums2[j] * nums2[k] < target) j++;\n        else k--;\n      }\n    }\n    return ans;\n  }\n};\n```
['JavaScript']