I scan the array once and treat each index j as the middle of a potential triplet. I keep two frequency maps: right initially counts all elements to the right of j (including j at start) and left counts elements to the left of j. For each j I remove nums[j] from right, compute target = 2 * nums[j], then the number of special triplets with this j as middle equals left[target] * right[target]. I add that to the answer and then add nums[j] into left before moving on. I take results mod 10^9+7.
class Solution:
def specialTriplets(self, nums: List[int]) -> int:
MOD = 10**9 + 7
n = len(nums)
right = Counter(nums)
left = Counter()
ans = 0
for j in range(n):
x = nums[j]
right[x] -= 1
if right[x] == 0:
del right[x]
target = 2 * x
if target in left and target in right:
ans = (ans + left[target] * right[target]) % MOD
left[x] += 1
return ans % MOD- Time: O(n)
- Space: O(n)