File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
kotlin/Hash Maps and Sets Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments