Skip to content

Commit d7fa10e

Browse files
committed
Add Geometric Sequence Triplets
1 parent 909f627 commit d7fa10e

File tree

1 file changed

+25
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)