3885. Count Special Triplets
My accepted Python solution to LeetCode problem 3885, Count Special Triplets, running in 557ms.
- Difficulty: Medium
- Python
- Runtime 557ms
- Memory 39.3MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 557ms, memory 39.3MB, accepted 2025-12-30.
class Solution:
def specialTriplets(self, nums: List[int]) -> int:
MOD = 10**9 + 7
n = len(nums)
# For each j, count i's before it where nums[i] = nums[j]*2
# and k's after it where nums[k] = nums[j]*2
# First pass: count occurrences of each value for suffix
suffix_count = {}
for num in nums:
suffix_count[num] = suffix_count.get(num, 0) + 1
prefix_count = {}
result = 0
for j in range(n):
target = nums[j] * 2
# Remove current element from suffix
suffix_count[nums[j]] -= 1
# Count triplets with j as middle element
left_count = prefix_count.get(target, 0)
right_count = suffix_count.get(target, 0)
result = (result + left_count * right_count) % MOD
# Add current element to prefix
prefix_count[nums[j]] = prefix_count.get(nums[j], 0) + 1
return result