-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount-triplets.js
42 lines (31 loc) · 1.01 KB
/
count-triplets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/***
Function Description
Complete the countTriplets function in the editor below. It should return the number of triplets forming a geometric progression for a given as an integer.
countTriplets has the following parameter(s):
arr: an array of integers
r: an integer, the common ratio
Sample Input
2
1 2 2 4
Sample Output 0
2
Explanation 0
There are triplets in satisfying our criteria, whose indices are and
**/
// Complete the countTriplets function below.
function countTriplets(arr, r) {
const elementsFreqHash = {};
const tripletsHash = {};
let tripletCounter = 0;
for (let i = arr.length -1; i >= 0; i--) {
const t1 = arr[i];
const t2 = t1 * r;
const t3 = t2 * r;
tripletCounter += tripletsHash[t3] || 0;
tripletsHash[t2] ?
tripletsHash[t2] += elementsFreqHash[t2] || 0 :
tripletsHash[t2] = elementsFreqHash[t2] || 0
elementsFreqHash[t1] ? elementsFreqHash[t1]++ : elementsFreqHash[t1] = 1
}
return tripletCounter;
}