← All problems

3583. Count Special Triplets

MediumOpen on LeetCodeProblem statement

Problem Statement

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:

Java

Source file
class Solution {
    public int specialTriplets(int[] nums) {
        Map<Integer, Integer> freqTotal = new HashMap<>();
        int MOD = 1_000_000_007, ans = 0;
        for (int i : nums)
            freqTotal.put(i, freqTotal.getOrDefault(i, 0) + 1);
        Map<Integer, Integer> freqRunning = new HashMap<>();
        for (int i : nums) {
            if (i == 0)
                continue;
            freqRunning.put(i, freqRunning.getOrDefault(i, 0) + 1);
            int target = 2 * i;
            ans = (ans + freqRunning.getOrDefault(target, 0)
                    * (freqTotal.getOrDefault(target, 0) - freqRunning.getOrDefault(target, 0))) % MOD;
        }
        return (ans + Math.max(0, freqTotal.getOrDefault(0, 0) - 2)) % MOD;
    }
}