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: 2
💡 Note: Two valid triplets: (0,1,2) where nums[0]=2, nums[1]=4, nums[2]=8 (2=4*2 is false, invalid). Actually valid triplets are (1,2,4) and (1,3,4) where middle elements 4 have 8's on both sides.
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: Find (i,j,k) where nums[i]=nums[k]=nums[j]*22484801234Special triplet condition:nums[i] = nums[k] = nums[j] × 2Valid: (1,2,4) → nums[1]=4, nums[2]=8, nums[4]=8Check: 8 = 4×2 ✓ and 8 = 4×2 ✓Total Special Triplets: 2
Understanding the Visualization
1
Input
Array [2,4,8,4,8] with indices 0,1,2,3,4
2
Process
Find triplets (i,j,k) where nums[i]=nums[k]=nums[j]*2
3
Output
Count of valid special triplets
Key Takeaway
🎯 Key Insight: Fix the middle element and count valid pairs on left and right sides
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