#3583
Count Special Triplets
MediumArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use frequency maps to count occurrences of numbers before and after the current index, allowing efficient calculation of valid triplets.
⚙️
Algorithm
3 steps- 1Step 1: Create two frequency arrays: freqPrev for counts before index j and freqNext for counts after index j.
- 2Step 2: For each index j, calculate the number of valid i's and k's using freqPrev and freqNext.
- 3Step 3: Sum the contributions for each j to get the total count of special triplets.
solution.py17 lines
1def countTriplets(nums):
2 MOD = 10**9 + 7
3 n = len(nums)
4 freqPrev = {}
5 freqNext = {}
6 for num in nums:
7 freqNext[num] = freqNext.get(num, 0) + 1
8 count = 0
9 for j in range(n):
10 freqNext[nums[j]] -= 1
11 if j > 0:
12 freqPrev[nums[j-1]] = freqPrev.get(nums[j-1], 0) + 1
13 if nums[j] % 2 == 0:
14 target = nums[j] // 2
15 count += freqPrev.get(target, 0) * freqNext.get(nums[j], 0)
16 count %= MOD
17 return countℹ
Complexity note: We traverse the array a couple of times, and use maps to store frequencies, leading to linear complexity.
- 1Using frequency maps allows efficient counting of valid triplets.
- 2The condition for special triplets relies on simple arithmetic relationships.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.