LeetCode in Kotlin

3583. Count Special Triplets

Medium

You are given an integer array nums.

A special triplet is defined as a triplet of indices (i, j, k) such that:

Return the total number of special triplets in the array.

Since the answer may be large, return it modulo 109 + 7.

Example 1:

Input: nums = [6,3,6]

Output: 1

Explanation:

The only special triplet is (i, j, k) = (0, 1, 2), where:

Example 2:

Input: nums = [0,1,0,0]

Output: 1

Explanation:

The only special triplet is (i, j, k) = (0, 2, 3), where:

Example 3:

Input: nums = [8,4,2,8,4]

Output: 2

Explanation:

There are exactly two special triplets:

Constraints:

Solution

class Solution {
    fun specialTriplets(nums: IntArray): Int {
        val mod = 1_000_000_007
        var res = 0
        val left = mutableMapOf<Int, Int>()
        val right = mutableMapOf<Int, Int>()
        for (num in nums) {
            right[num] = right.getOrDefault(num, 0) + 1
        }
        for (num in nums) {
            right[num] = right[num]!! - 1
            val ci = left.getOrDefault(num * 2, 0)
            val ck = right.getOrDefault(num * 2, 0)
            res = ((res + 1L * ci * ck) % mod).toInt()
            left[num] = left.getOrDefault(num, 0) + 1
        }
        return res
    }
}