Count Special Quadruplets - Problem

Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:

  • nums[a] + nums[b] + nums[c] == nums[d], and
  • a < b < c < d

You need to find all valid combinations where three numbers sum to equal a fourth number, with all indices in strictly increasing order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,0,1,0,2]
Output: 1
💡 Note: The only valid quadruplet is (0,1,2,4): nums[0] + nums[1] + nums[2] = 1 + 0 + 1 = 2 = nums[4], and 0 < 1 < 2 < 4
Example 2 — No Valid Quadruplets
$ Input: nums = [2,2,2,2]
Output: 0
💡 Note: No valid quadruplet exists because 2 + 2 + 2 = 6 ≠ 2. All elements are the same but the sum of any three doesn't equal the fourth
Example 3 — Multiple Quadruplets
$ Input: nums = [1,1,1,3,5]
Output: 2
💡 Note: Two valid quadruplets: (0,1,2,3) where 1+1+1=3, and (0,1,3,4) where 1+1+3=5

Constraints

  • 4 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Count Special Quadruplets: Find nums[a] + nums[b] + nums[c] = nums[d]Input Array:10102a=0b=1c=23d=4Check condition: nums[0] + nums[1] + nums[2] ?= nums[4]1 + 0 + 1 = 2 ✓Sum of first three1 + 0 + 1 = 2Fourth elementnums[4] = 2Result: 1 valid quadruplet found (0,1,2,4)
Understanding the Visualization
1
Input Array
Array with indices a < b < c < d
2
Find Condition
Check if nums[a] + nums[b] + nums[c] == nums[d]
3
Count Results
Return total number of valid quadruplets
Key Takeaway
🎯 Key Insight: Transform quadruplet search into efficient sum lookup using hash maps
Asked in
Google 15 Amazon 12 Microsoft 8
32.0K Views
Medium Frequency
~15 min Avg. Time
890 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