3583. Count Special Triplets
Description
You are given an integer array nums.
A special triplet is defined as a triplet of indices (i, j, k) such that:
0 <= i < j < k < n, wheren = nums.lengthnums[i] == nums[j] * 2nums[k] == nums[j] * 2
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:
nums[0] = 6,nums[1] = 3,nums[2] = 6nums[0] = nums[1] * 2 = 3 * 2 = 6nums[2] = nums[1] * 2 = 3 * 2 = 6
Example 2:
Input: nums = [0,1,0,0]
Output: 1
Explanation:
The only special triplet is (i, j, k) = (0, 2, 3), where:
nums[0] = 0,nums[2] = 0,nums[3] = 0nums[0] = nums[2] * 2 = 0 * 2 = 0nums[3] = nums[2] * 2 = 0 * 2 = 0
Example 3:
Input: nums = [8,4,2,8,4]
Output: 2
Explanation:
There are exactly two special triplets:
(i, j, k) = (0, 1, 3)nums[0] = 8,nums[1] = 4,nums[3] = 8nums[0] = nums[1] * 2 = 4 * 2 = 8nums[3] = nums[1] * 2 = 4 * 2 = 8
(i, j, k) = (1, 2, 4)nums[1] = 4,nums[2] = 2,nums[4] = 4nums[1] = nums[2] * 2 = 2 * 2 = 4nums[4] = nums[2] * 2 = 2 * 2 = 4
Constraints:
3 <= n == nums.length <= 1050 <= nums[i] <= 105
Solutions
Solution: Hash Map
- Time complexity: O(n)
- Space complexity: O(n)
JavaScript
js
/**
* @param {number[]} nums
* @return {number}
*/
const specialTriplets = function (nums) {
const MODULO = 10 ** 9 + 7;
const n = nums.length;
const numMap = new Map();
const partialMap = new Map();
let result = 0;
for (let index = 0; index < n; index++) {
const num = nums[index];
const count = numMap.get(num) ?? 0;
numMap.set(num, count + 1);
}
for (let index = 0; index < n; index++) {
const num = nums[index];
const count = partialMap.get(num) ?? 0;
const target = num * 2;
const prefixCount = partialMap.get(target);
partialMap.set(num, count + 1);
if (prefixCount) {
const suffixCount = numMap.get(target) - partialMap.get(target);
result = (result + prefixCount * suffixCount) % MODULO;
}
}
return result;
};