Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created December 9, 2025 22:31
Show Gist options
  • Select an option

  • Save Ifihan/9a27531b254298318bd1b4ad8c6c8401 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/9a27531b254298318bd1b4ad8c6c8401 to your computer and use it in GitHub Desktop.
Count Special Triplets

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment