3583. Count Special Triplets #2514
-
|
Topics: You are given an integer array nums. A special triplet is defined as a triplet of indices
Return the total number of special triplets in the array. Since the answer may be large, return it modulo Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We could also use prefix and suffix arrays to store counts of each value at each position, but that would require O(n * max_val) space which is inefficient for large values. The hash table approach is more memory efficient for sparse value distributions. Approach:
Let's implement this solution in PHP: 3583. Count Special Triplets <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function specialTriplets($nums) {
$MOD = 1000000007;
$n = count($nums);
// Frequency maps
$leftFreq = [];
$rightFreq = [];
// Initialize right frequency with all elements
foreach ($nums as $num) {
$rightFreq[$num] = ($rightFreq[$num] ?? 0) + 1;
}
$total = 0;
for ($j = 0; $j < $n; $j++) {
// Remove current element from right frequency
$rightFreq[$nums[$j]]--;
// Calculate target value = 2 * nums[j]
$target = $nums[$j] * 2;
// Get counts from left and right
$leftCount = $leftFreq[$target] ?? 0;
$rightCount = $rightFreq[$target] ?? 0;
// Add to total (modulo 10^9+7)
$total = ($total + ($leftCount * $rightCount)) % $MOD;
// Add current element to left frequency
$leftFreq[$nums[$j]] = ($leftFreq[$nums[$j]] ?? 0) + 1;
}
return $total;
}
// Test cases
echo specialTriplets([6,3,6]) . "\n"; // Output: 1
echo specialTriplets([0,1,0,0]) . "\n"; // Output: 1
echo specialTriplets([8,4,2,8,4]) . "\n"; // Output: 2
?>Explanation:
|
Beta Was this translation helpful? Give feedback.
We could also use prefix and suffix arrays to store counts of each value at each position, but that would require O(n * max_val) space which is inefficient for large values. The hash table approach is more memory efficient for sparse value distributions.
Approach:
leftFreq) and one for elements after current index (rightFreq).jas the middle element of potential triplets.jfrom left to right:rightFreq(since it's no longer on the right)2 * nums[j]ipo…