Skip to main content

1726.js

/** ------------------------------------------------------------------------------
*
* 1726. Tuple with Same Product
* Topics: Array, Hash Table
* https://leetcode.com/problems/tuple-with-same-product/?envType=daily-question&envId=2025-02-06
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} nums
* @return {number}
*/
var tupleSameProduct = function (nums) {
const n = nums.length
const map = new Map()
let count = 0

for (let i = 0; i < n; i++) {
const a = nums[i]

for (let j = i + 1; j < n; j++) {
const b = nums[j]

const product = a * b
const pairs = map.get(product) || 0

count += pairs * 8

map.set(product, pairs + 1)
}
}

return count
}

var tupleSameProduct = function (nums) {
const map = new Map()
let count = 0
let n = nums.length
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let product = nums[i] * nums[j]
map.set(product, (map.get(product) || 0) + 1)
}
}

for (let freq of map.values()) {
if (freq > 1) {
count += ((freq * (freq - 1)) / 2) * 8
}
}
return count
}

console.log(tupleSameProduct([2, 3, 4, 6, 8, 12]))