Count Special Triplets - Problem

You are given an integer array nums. A special triplet is defined as a triplet of indices (i, j, k) such that:

  • 0 <= i < j < k < n, where n = nums.length
  • nums[i] == nums[j] * 2
  • nums[k] == nums[j] * 2

Return the total number of special triplets in the array. Since the answer may be large, return it modulo 10^9 + 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,4,8,4,8]
Output: 1
💡 Note: Only one valid triplet exists: (2,3,4) where nums[2]=8, nums[3]=4, nums[4]=8. Here 8 == 4*2 and 8 == 4*2, satisfying both conditions.
Example 2 — No Valid Triplets
$ Input: nums = [1,2,3,4,5]
Output: 0
💡 Note: No valid triplets exist since no element equals another element times 2 in the required positions.
Example 3 — Multiple Matches
$ Input: nums = [4,2,4,2,4]
Output: 4
💡 Note: Multiple triplets where middle element 2 has 4's (2*2=4) on both sides, creating several valid combinations.

Constraints

  • 3 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Count Special Triplets INPUT nums = [2, 4, 8, 4, 8] 2 i=0 4 i=1 8 i=2 4 i=3 8 i=4 Special Triplet (i,j,k): 0 <= i < j < k < n nums[i] == nums[j] * 2 nums[k] == nums[j] * 2 Valid Triplets Found: Triplet 1: (1,2,4) 4*2=8, 4*2=8 [OK] Triplet 2: (3,2,4) 4*2=8, 4*2=8 [OK] ALGORITHM STEPS 1 Initialize Freq map, count=0 2 Iterate j (middle) For each j position 3 Count pairs left[j*2] * right[j*2] 4 Update frequency Move j, update maps Frequency Tracking j=2 (val=8): left: {2:1, 4:1} right: {4:1, 8:1} Need: 16 (none) For j=1,3: val=4 count += left[8]*right[8] FINAL RESULT Special Triplets Found: Triplet 1: (1, 2, 4) nums[1]=4, nums[2]=8, nums[4]=8 4*2=8 [OK], 4*2=8 [OK] Triplet 2: (3, 2, 4) nums[3]=4, nums[2]=8, nums[4]=8 4*2=8 [OK], 4*2=8 [OK] OUTPUT 2 Total special triplets return 2 % (10^9 + 7) Key Insight: For middle element j with value v, count valid triplets by tracking frequency of elements before and after j. We need nums[i] = v*2 on left and nums[k] = v*2 on right. Multiply left_freq[v*2] * right_freq[v*2]. Time: O(n), Space: O(n) using hash maps for frequency tracking. TutorialsPoint - Count Special Triplets | Optimized with Frequency Count
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen