Skip to content

Commit 143fcd7

Browse files
committed
Add solution #3583
1 parent dc674c3 commit 143fcd7

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2786,6 +2786,7 @@
27862786
3539|[Find Sum of Array Product of Magical Sequences](./solutions/3539-find-sum-of-array-product-of-magical-sequences.js)|Hard|
27872787
3541|[Find Most Frequent Vowel and Consonant](./solutions/3541-find-most-frequent-vowel-and-consonant.js)|Easy|
27882788
3578|[Count Partitions With Max-Min Difference at Most K](./solutions/3578-count-partitions-with-max-min-difference-at-most-k.js)|Medium|
2789+
3583|[Count Special Triplets](./solutions/3583-count-special-triplets.js)|Medium|
27892790
3623|[Count Number of Trapezoids I](./solutions/3623-count-number-of-trapezoids-i.js)|Medium|
27902791

27912792
## License
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 3583. Count Special Triplets
3+
* https://leetcode.com/problems/count-special-triplets/
4+
* Difficulty: Medium
5+
*
6+
* You are given an integer array nums.
7+
*
8+
* A special triplet is defined as a triplet of indices (i, j, k) such that:
9+
* - 0 <= i < j < k < n, where n = nums.length
10+
* - nums[i] == nums[j] * 2
11+
* - nums[k] == nums[j] * 2
12+
*
13+
* Return the total number of special triplets in the array.
14+
*
15+
* Since the answer may be large, return it modulo 109 + 7.
16+
*/
17+
18+
/**
19+
* @param {number[]} nums
20+
* @return {number}
21+
*/
22+
var specialTriplets = function(nums) {
23+
const MOD = 1e9 + 7;
24+
let result = 0;
25+
26+
const leftCount = new Map();
27+
const rightCount = new Map();
28+
for (const num of nums) {
29+
rightCount.set(num, (rightCount.get(num) || 0) + 1);
30+
}
31+
32+
for (let j = 0; j < nums.length; j++) {
33+
const middle = nums[j];
34+
const target = middle * 2;
35+
36+
rightCount.set(middle, rightCount.get(middle) - 1);
37+
if (rightCount.get(middle) === 0) {
38+
rightCount.delete(middle);
39+
}
40+
41+
const left = leftCount.get(target) || 0;
42+
const right = rightCount.get(target) || 0;
43+
result = (result + left * right) % MOD;
44+
leftCount.set(middle, (leftCount.get(middle) || 0) + 1);
45+
}
46+
47+
return result;
48+
};

0 commit comments

Comments
 (0)