You are viewing a single comment's thread. Return to all comments →
javascript
this version is more intuitive but fails on case 3. the version down below improved performance based on it.
function countTriplets(arr, r) { let map = new Map(), count = 0 for (let i = 0; i < arr.length; i++) { if (map.has(arr[i])) map.get(arr[i]).push(i) else map.set(arr[i], [i]) } for (let i = 0; i < arr.length; i++) { let cur = arr[i] if (map.has(cur / r) && map.has(cur * r)) { count += map.get(cur / r).filter(idx => idx < i).length * map.get(cur * r).filter(idx => idx > i).length } } return count }
function countTriplets(arr, r) { let map = new Map(), count = 0 for (let i = 0; i < arr.length; i++) { if (map.has(arr[i])) map.get(arr[i]).push(i) else map.set(arr[i], [i]) } for (let i = 1; i < arr.length - 1; i++) { let cur = arr[i] if (map.has(cur / r) && map.has(cur * r)) { let leftIndex = map.get(cur / r).findIndex(idx => idx > i) let rightIndex = map.get(cur * r).findIndex(idx => idx > i) let howManyLeft = leftIndex == -1 ? map.get(cur / r).length : leftIndex let howManyRight = rightIndex == -1 ? 0 : map.get(cur * r).length - rightIndex count += (r == 1 ? howManyLeft - 1 : howManyLeft) * howManyRight } } return count }
Seems like cookies are disabled on this browser, please enable them to open this website
Count Triplets
You are viewing a single comment's thread. Return to all comments →
javascript
this version is more intuitive but fails on case 3. the version down below improved performance based on it.