Skip to content

Commit 116944e

Browse files
committed
feat: add geometric sequence triplets solution
1 parent aa3a789 commit 116944e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,27 @@
11
package hashmapsandsets
2+
3+
func GeometricSequenceTriplets(nums []int, r int) int {
4+
// Use 'map' to ensure the default value of 0 is returned when
5+
// accessing a key that doesn’t exist in the hash map. This effectively sets
6+
// the default frequency of all elements to 0.
7+
leftMap := make(map[int]int)
8+
rightMap := make(map[int]int)
9+
count := 0
10+
// Populate 'rightMap' with the frequency of each element in the array.
11+
for _, x := range nums {
12+
rightMap[x]++
13+
}
14+
// Search for geometric triplets that have x as the center.
15+
for _, x := range nums {
16+
// Decrement the frequency of x in 'rightMap' since x is now being
17+
// processed and is no longer to the right.
18+
rightMap[x]--
19+
if x%r == 0 {
20+
count += leftMap[x/r] * rightMap[x*r]
21+
}
22+
// Increment the frequency of x in 'leftMap' since it'll be a part of the
23+
// left side of the array once we iterate to the next value of x.
24+
leftMap[x]++
25+
}
26+
return count
27+
}

0 commit comments

Comments
 (0)