Count Special Quadruplets - Problem

Given a 0-indexed integer array nums, you need to find all special quadruplets that satisfy a unique mathematical relationship.

A quadruplet (a, b, c, d) is considered special if:

  • nums[a] + nums[b] + nums[c] == nums[d] (the sum of first three elements equals the fourth)
  • a < b < c < d (indices are in strictly increasing order)

Your task is to count how many distinct special quadruplets exist in the given array.

Example: In array [1,0,1,0,2], the quadruplet at indices (0,1,2,4) is special because nums[0] + nums[1] + nums[2] = 1 + 0 + 1 = 2 = nums[4].

Input & Output

example_1.py — Basic Case
$ Input: [1,0,1,0,2]
› Output: 1
šŸ’” Note: The quadruplet (0,1,2,4) is special because nums[0] + nums[1] + nums[2] = 1 + 0 + 1 = 2 = nums[4]
example_2.py — Multiple Quadruplets
$ Input: [2,2,2,2]
› Output: 0
šŸ’” Note: No special quadruplets exist because 2 + 2 + 2 = 6 ≠ 2
example_3.py — Edge Case
$ Input: [1,1,1,3,5]
› Output: 2
šŸ’” Note: Two quadruplets: (0,1,2,3) where 1+1+1=3, and (0,1,3,4) where 1+1+3=5

Visualization

Tap to expand
šŸŽÆ Team Formation Strategy1Member A0Member B1Assistant2Team Leader1+0=1Need: 2-1=1āœ“ Perfect Match!Pair (A,B) has skill sum = 1Leader needs exactly 1 to reach skill 2Hash table helps us find such pairs instantly!šŸ’” Key Insight: Fix the end positions and efficiently count valid beginnings
Understanding the Visualization
1
Choose Team Leader
Pick the strongest member (rightmost position d) as team leader
2
Select Assistant
Choose an assistant (position c) from remaining candidates
3
Calculate Need
Determine what skill combination we need: target = leader_skill - assistant_skill
4
Count Valid Pairs
Use our database to quickly count how many pairs have the target skill sum
Key Takeaway
šŸŽÆ Key Insight: Instead of checking all combinations, fix the last two positions and use a hash table to efficiently count how many valid pairs exist for the first two positions.

Time & Space Complexity

Time Complexity
ā±ļø
O(n³)

Three nested loops, but inner operations are O(1) hash lookups

n
2n
⚠ Quadratic Growth
Space Complexity
O(n²)

Hash table stores pair sums, potentially O(n²) different sums

n
2n
⚠ Quadratic Space

Constraints

  • 4 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 100
  • Array must have at least 4 elements to form a quadruplet
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
28.5K Views
Medium Frequency
~18 min Avg. Time
892 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