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 quadruplets where nums[a] + nums[b] + nums[c] == nums[d] with a < b < c < d INPUT nums = [1, 0, 1, 0, 2] 1 a=0 0 b=1 1 c=2 0 d=3 2 d=4 Condition: nums[a]+nums[b]+nums[c] == nums[d] where a < b < c < d Valid Quadruplet: (0,1,2,4): 1+0+1 = 2 ALGORITHM STEPS 1 Init Hash Map Store diff = nums[d]-nums[c] 2 Iterate Backwards c from n-2 to 1 3 Check Pairs (a,b) sum = nums[a]+nums[b] 4 Count Matches count += map[sum] Hash Map (diff counts) Key (diff) Count 2 1 When sum(a,b) = 1+0+1 = 2 map[2] exists --> count++ FINAL RESULT Output: 1 Valid Quadruplet Found: (a,b,c,d) = (0,1,2,4) nums: [1,0,1,_,2] 1 + 0 + 1 = 2 [OK] Complexity Analysis Time: O(n^2) Space: O(n^2) vs O(n^4) brute force Key Insight: Transform nums[a]+nums[b]+nums[c]=nums[d] into nums[a]+nums[b] = nums[d]-nums[c]. Use hash map to store differences (nums[d]-nums[c]) and count matching sums (nums[a]+nums[b]). Process from right to left to maintain index ordering constraint a < b < c < d automatically. TutorialsPoint - Count Special Quadruplets | Hash Map Optimization
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