Last active
September 2, 2020 16:10
-
-
Save okiroth/d2b434189d57694d605a3d152c635dbf to your computer and use it in GitHub Desktop.
Find ordered geometric progressions of 3 numbers in array. O(n)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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