LeetCode Challenge Day 85 β 3583. Count Special Triplets
Nitin Ahirwal / December 9, 2025
Hey folks π
This is Day 85 of my LeetCode streak π
Today's problem is 3583. Count Special Triplets β a medium problem that rewards careful observation and an efficient counting strategy.
π Problem Statement
You are given an integer array nums.
A special triplet (i, j, k) must satisfy:
0 β€ i < j < k < nnums[i] = nums[j] * 2nums[k] = nums[j] * 2
Return the total number of special triplets, modulo 10βΉ + 7.
Example:
Input: nums = [8,4,2,8,4]
Output: 2
Explanation:
(0, 1, 3) β 8, 4, 8
(1, 2, 4) β 4, 2, 4
π‘ Intuition
For every valid triplet, the middle element nums[j] determines the value of both nums[i] and nums[k].
So instead of brute-forcing all (i, j, k) combinations, we can:
-
Fix the middle index
j -
Count how many times
nums[j] * 2appears beforej -
Count how many times
nums[j] * 2appears afterj
The number of valid triplets for that j is simply the product of these two counts.
π Approach
-
Maintain two frequency arrays:
-
left[x]β count of valuexappearing before indexj -
right[x]β count of valuexappearing after indexj
-
-
Initialize
rightwith the frequency of all elements. -
Traverse the array from left to right, treating each index as
j:-
Remove
nums[j]fromright -
Compute
target = nums[j] * 2 -
Add
left[target] * right[target]to the answer -
Add
nums[j]toleft
-
-
Apply modulo
10βΉ + 7throughout to prevent overflow.
This ensures each valid triplet is counted once, efficiently.
β±οΈ Complexity Analysis
-
Time Complexity:
O(n)β We traverse the array once while doing constant-time operations. -
Space Complexity:
O(U)β Extra space is used for frequency arrays, where
U = 10^5(maximum possible value innums).
π§βπ» Code (JavaScript)
/**
* @param {number[]} nums
* @return {number}
*/
var specialTriplets = function(nums) {
const MOD = 1_000_000_007;
const n = nums.length;
if (n < 3) return 0;
const MAX = 100000;
// right[x] = count of value x for indices > j
const right = new Array(MAX + 1).fill(0);
for (const v of nums) {
right[v]++;
}
// left[x] = count of value x for indices < j
const left = new Array(MAX + 1).fill(0);
let ans = 0;
for (let j = 0; j < n; j++) {
const v = nums[j];
// current element can no longer serve as k
right[v]--;
const target = v * 2;
if (target <= MAX) {
ans = (ans + (left[target] * right[target]) % MOD) % MOD;
}
// current element becomes available as i
left[v]++;
}
return ans;
};
π― Reflection
This problem highlights how:
-
Fixing one index can dramatically simplify a multi-index problem
-
Frequency counting + prefix/suffix thinking avoids brute force
-
Index order constraints (
i < j < k) matter just as much as values
Thatβs it for Day 85 of my LeetCode challenge πͺ
Streak continues π₯
Happy Coding π¨βπ»