Last active
December 9, 2025 17:11
-
-
Save tatsuyax25/c064386a72b714325f8f3d042f5ee927 to your computer and use it in GitHub Desktop.
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, where n = nums.length
nums[i] == nums[j] * 2
nums[k] == nums[j] * 2
Return the total number of special triplets in th
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| */ | |
| var specialTriplets = function(nums) { | |
| const MOD = 1e9 + 7; // modulus to avoid overflow | |
| const n = nums.length; | |
| // Frequency maps | |
| let leftCount = new Map(); // counts of numbers before j | |
| let rightCount = new Map(); // counts of numbers after j | |
| // Initialize rightCount with all numbers | |
| for (let num of nums) { | |
| rightCount.set(num, (rightCount.get(num) || 0) + 1); | |
| } | |
| let result = 0; | |
| // Iterate through each possible j | |
| for (let j = 0; j < n; j++) { | |
| let val = nums[j]; | |
| // Remove nums[j] from rightCount since j is now the "middle" | |
| rightCount.set(val, rightCount.get(val) - 1); | |
| if (rightCount.get(val) === 0) { | |
| rightCount.delete(val); | |
| } | |
| // Condition: nums[i] == 2 * nums[j] | |
| let target = val * 2; | |
| // Count how many i < j satisfy nums[i] == target | |
| let countLeft = leftCount.get(target) || 0; | |
| // Count how many k > j satisfy nums[k] == target | |
| let countRight = rightCount.get(target) || 0; | |
| // Each pair (i, k) with this j forms a valid triplet | |
| result = (result + (countLeft * countRight) % MOD) % MOD; | |
| // Add nums[j] to leftCount for future iterations | |
| leftCount.set(val, (leftCount.get(val) || 0) + 1); | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment