Skip to content

Instantly share code, notes, and snippets.

@okiroth
Last active September 2, 2020 16:10
Show Gist options
  • Select an option

  • Save okiroth/d2b434189d57694d605a3d152c635dbf to your computer and use it in GitHub Desktop.

Select an option

Save okiroth/d2b434189d57694d605a3d152c635dbf to your computer and use it in GitHub Desktop.
Find ordered geometric progressions of 3 numbers in array. O(n)
function countTriplets(arr, r) {
let pairs = {}
let freq = {}
let count = 0
arr.reverse().forEach(a => {
let b = a * r
if (b in pairs) {
count += pairs[b]
}
if (b in freq) {
pairs[a] = !pairs[a] ? freq[b] : pairs[a] + freq[b]
}
freq[a] = !freq[a] ? 1 : freq[a] + 1
// console.log({a, b, pairs, freq, count})
})
return count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment