Talentd
FleetCode
Make and follow sheets.Sign in

Count Special Quadruplets solution and explanation

EasyArrayEnumerationHash Table5 min read65.1% acceptanceUpdated 9 Apr 2026
1995. Count Special Quadruplets (Leetcode Easy)Programming Live with Larry · 3:35 · 2K viewsWatch on YouTube
9 more videos on this problem
  1. 1995. Count Special Quadruplets (Leetcode Easy)Programming Live with Larry · 3:35 · 2K views
  2. 1995. Count Special Quadruplets | LEETCODE EASYcode Explainer · 10:15 · 1K views
  3. Count special quadruplets | Count special quadruplets leetcode | leetcode 1995 | #leetcode1995|codeCoderNight · 1:42 · 487 views
  4. Count Special QuadrupletsCode with Bogus Engineer · 8:55 · 377 views
  5. LeetCode 1995 | Count Special Quadruplets | JavaSleepy Cracker · 9:48 · 323 views
  6. Count Special Quadruplets #leetcode 1995Vaibhav Gulati · 0:36 · 123 views
  7. Counting Unique Quadruplets: Leetcode problem 1995: An explanationPewaukee · 40:37 · 79 views
  8. Day 335: LeetCode Problem 1995. Count Special Quadruplets - SwiftiOSxBank · 11:05 · 62 views
  9. LeetCode 1995 - Count Special Quadruplets | Beginner Friendly C++ SolutionDhvanit · 4:33 · 8 views
  10. LeetCode 1995: Count Special QuadrupletsAlitaCode · 26:52 · 4 views

The 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

Example 1:

Input: nums = [1,2,3,6]
Output: 1
Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.

Example 2:

Input: nums = [3,3,6,4,5]
Output: 0
Explanation: There are no such quadruplets in [3,3,6,4,5].

Example 3:

Input: nums = [1,1,1,3,5]
Output: 4
Explanation: The 4 quadruplets that satisfy the requirement are:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5

Constraints:

  • 4 <= nums.length <= 50
  • 1 <= nums[i] <= 100

Approach overview

Problem Overview: Given an integer array nums, count the number of quadruplets (a, b, c, d) such that a < b < c < d and nums[a] + nums[b] + nums[c] == nums[d]. The task is essentially finding ordered index combinations where the sum of three earlier elements equals a later element.

Approach 1: Naive Brute Force Enumeration (O(n4) time, O(1) space)

The most direct solution enumerates every possible quadruplet using four nested loops. The loops enforce the index constraint a < b < c < d. For each combination, compute nums[a] + nums[b] + nums[c] and compare it with nums[d]. If they match, increment the count. This approach is easy to implement and useful for understanding the structure of the problem, but the O(n4) runtime grows quickly as the array size increases. It mainly serves as a baseline enumeration technique for problems involving ordered index tuples in arrays.

Approach 2: Optimized Hash Map Approach (O(n2) time, O(n) space)

The key observation is that the equation nums[a] + nums[b] + nums[c] = nums[d] can be rearranged to nums[a] + nums[b] = nums[d] - nums[c]. Instead of checking all quadruplets, store differences (nums[d] - nums[c]) in a hash map while scanning from the right side of the array. Then iterate pairs (a, b) on the left and check whether their sum appears in the map. Each lookup is O(1) on average, turning the nested search into roughly O(n2). The map tracks how many valid (c, d) combinations produce a specific difference. This technique leverages constant‑time lookups from a hash table and reduces redundant enumeration.

This optimization works because the index ordering constraint allows the array to be split into two regions: pairs on the left and pairs on the right. By converting the equality condition into a difference lookup, you avoid repeatedly recomputing the same combinations. This is a common pattern in problems involving sums, pair matching, and enumeration with constraints.

Recommended for interviews: Start by explaining the brute force idea to demonstrate you understand the ordering constraint and the equation structure. Then derive the hash map optimization by rearranging the equation into a pair‑sum vs difference lookup. Interviewers usually expect the optimized O(n2) approach because it shows you can reduce multi‑loop enumeration using hashing.

Approach 1: Naive Brute Force Approach

This approach involves iterating through all combinations of four distinct indices (a, b, c, d) and checking if they satisfy the condition nums[a] + nums[b] + nums[c] == nums[d]. Loop every possible index to find all such quadruplets and count them.

def countQuadruplets(nums):
    count = 0
    n = len(nums)
    for a in range(n - 3):
        for b in range(a + 1, n - 2):
            for c in range(b + 1, n - 1):
                for d in range(c + 1, n):
                    if nums[a] + nums[b] + nums[c] == nums[d]:
                        count += 1
    return count

# Example usage
nums = [1, 2, 3, 6]
print("Count of quadruplets:", countQuadruplets(nums))
public class Solution {
    public int countQuadruplets(int[] nums) {
        int count = 0;
        int n = nums.length;
        for (int a = 0; a < n - 3; a++) {
            for (int b = a + 1; b < n - 2; b++) {
                for (int c = b + 1; c < n - 1; c++) {
                    for (int d = c + 1; d < n; d++) {
                        if (nums[a] + nums[b] + nums[c] == nums[d]) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums = {1, 2, 3, 6};
        System.out.println("Count of quadruplets: " + sol.countQuadruplets(nums));
    }
}
#include <vector>
#include <iostream>

int countQuadruplets(std::vector<int>& nums) {
    int count = 0;
    int n = nums.size();
    for (int a = 0; a < n - 3; ++a) {
        for (int b = a + 1; b < n - 2; ++b) {
            for (int c = b + 1; c < n - 1; ++c) {
                for (int d = c + 1; d < n; ++d) {
                    if (nums[a] + nums[b] + nums[c] == nums[d]) {
                        ++count;
                    }
                }
            }
        }
    }
    return count;
}

int main() {
    std::vector<int> nums = {1, 2, 3, 6};
    std::cout << "Count of quadruplets: " << countQuadruplets(nums) << std::endl;
    return 0;
}
function countQuadruplets(nums) {
    let count = 0;
    let n = nums.length;
    for (let a = 0; a < n - 3; a++) {
        for (let b = a + 1; b < n - 2; b++) {
            for (let c = b + 1; c < n - 1; c++) {
                for (let d = c + 1; d < n; d++) {
                    if (nums[a] + nums[b] + nums[c] === nums[d]) {
                        count++;
                    }
                }
            }
        }
    }
    return count;
}

// Example usage
const nums = [1, 2, 3, 6];
console.log("Count of quadruplets:", countQuadruplets(nums));
#include <stdio.h>

int countQuadruplets(int* nums, int numsSize) {
    int count = 0;
    for (int a = 0; a < numsSize - 3; a++) {
        for (int b = a + 1; b < numsSize - 2; b++) {
            for (int c = b + 1; c < numsSize - 1; c++) {
                for (int d = c + 1; d < numsSize; d++) {
                    if (nums[a] + nums[b] + nums[c] == nums[d]) {
                        count++;
                    }
                }
            }
        }
    }
    return count;
}

int main() {
    int nums[] = {1, 2, 3, 6};
    int result = countQuadruplets(nums, 4);
    printf("Count of quadruplets: %d\n", result);
    return 0;
}
using System;

class Solution {
    public int CountQuadruplets(int[] nums) {
        int count = 0;
        int n = nums.Length;
        for (int a = 0; a < n - 3; a++) {
            for (int b = a + 1; b < n - 2; b++) {
                for (int c = b + 1; c < n - 1; c++) {
                    for (int d = c + 1; d < n; d++) {
                        if (nums[a] + nums[b] + nums[c] == nums[d]) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }

    static void Main() {
        Solution sol = new Solution();
        int[] nums = {1, 2, 3, 6};
        Console.WriteLine("Count of quadruplets: " + sol.CountQuadruplets(nums));
    }
}

In this Python version, four nested loops execute over list indices. The calculated sums are compared to the selected fourth element in the list to verify the distinct quadruplets.

Complexity

Time Complexity: O(n^4)
Space Complexity: O(1).

Try this approach in the editor

Approach 2: Optimized Hash Map Approach

The optimization focuses on reducing the number of loops by reversing the sum checking process. By using hash maps, you can precompute partial sums and efficiently check for matches.

def countQuadruplets(nums):
    count = 0
    hash_map = {}
    n = len(nums)
    for b in range(n - 3, 0, -1):
        for d in range(b + 2, n):
            diff = nums[d] - nums[b + 1]
            if diff not in hash_map:
                hash_map[diff] = 0
            hash_map[diff] += 1
        for a in range(b):
            sum_val = nums[a] + nums[b]
            if sum_val in hash_map:
                count += hash_map[sum_val]
    return count

# Example usage
nums = [1, 1, 1, 3, 5]
print("Count of quadruplets:", countQuadruplets(nums))
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int countQuadruplets(int[] nums) {
        int count = 0;
        Map<Integer, Integer> hash = new HashMap<>();
        int n = nums.length;
        for (int b = n - 3; b >= 1; b--) {
            for (int d = b + 2; d < n; d++) {
                hash.put(nums[d] - nums[b + 1], hash.getOrDefault(nums[d] - nums[b + 1], 0) + 1);
            }
            for (int a = 0; a < b; a++) {
                count += hash.getOrDefault(nums[a] + nums[b], 0);
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums = {1, 1, 1, 3, 5};
        System.out.println("Count of quadruplets: " + sol.countQuadruplets(nums));
    }
}
#include <vector>
#include <iostream>
#include <unordered_map>

int countQuadruplets(std::vector<int>& nums) {
    int count = 0;
    std::unordered_map<int, int> hash;
    int n = nums.size();
    for (int b = n - 3; b >= 1; --b) {
        for (int d = b + 2; d < n; ++d) {
            hash[nums[d] - nums[b + 1]]++;
        }
        for (int a = 0; a < b; ++a) {
            count += hash[nums[a] + nums[b]];
        }
    }
    return count;
}

int main() {
    std::vector<int> nums = {1, 1, 1, 3, 5};
    std::cout << "Count of quadruplets: " << countQuadruplets(nums) << std::endl;
    return 0;
}
function countQuadruplets(nums) {
    let count = 0;
    const n = nums.length;
    const hash = {};

    for (let b = n - 3; b >= 1; b--) {
        for (let d = b + 2; d < n; d++) {
            const diff = nums[d] - nums[b + 1];
            if (!(diff in hash)) hash[diff] = 0;
            hash[diff]++;
        }
        for (let a = 0; a < b; a++) {
            const sum = nums[a] + nums[b];
            if (hash[sum]) count += hash[sum];
        }
    }

    return count;
}

// Example usage
const nums = [1, 1, 1, 3, 5];
console.log("Count of quadruplets:", countQuadruplets(nums));
#include <stdio.h>
#include <string.h>

#define MAX 102

int countQuadruplets(int* nums, int numsSize) {
    int count = 0;
    int hash[MAX] = {0};

    for (int b = numsSize - 3; b >= 1; b--) {
        for (int d = b + 2; d < numsSize; d++) {
            hash[nums[d] - nums[b + 1]]++;
        }
        for (int a = 0; a < b; a++) {
            count += hash[nums[a] + nums[b]];
        }
    }
    return count;
}

int main() {
    int nums[] = {1, 1, 1, 3, 5};
    int result = countQuadruplets(nums, 5);
    printf("Count of quadruplets: %d\n", result);
    return 0;
}
using System;
using System.Collections.Generic;

class Solution {
    public int CountQuadruplets(int[] nums) {
        int count = 0;
        Dictionary<int, int> hash = new Dictionary<int, int>();
        int n = nums.Length;
        for (int b = n - 3; b >= 1; b--) {
            for (int d = b + 2; d < n; d++) {
                int diff = nums[d] - nums[b + 1];
                if (!hash.ContainsKey(diff)) hash[diff] = 0;
                hash[diff]++;
            }
            for (int a = 0; a < b; a++) {
                int sum = nums[a] + nums[b];
                if (hash.ContainsKey(sum)) count += hash[sum];
            }
        }
        return count;
    }

    static void Main() {
        Solution sol = new Solution();
        int[] nums = {1, 1, 1, 3, 5};
        Console.WriteLine("Count of quadruplets: " + sol.CountQuadruplets(nums));
    }
}

The Python solution utilizes dictionaries to maintain differences as keys. The array is iterated in reverse, providing quicker lookups for determining counts of suitable quadruplets.

Complexity

Time Complexity: O(n^3).
Space Complexity: O(n) for dictionary maintenance.

Try this approach in the editor

Approach 3: Default Approach

func countQuadruplets(nums []int) int {
	ans, n := 0, len(nums)
	for a := 0; a < n-3; a++ {
		for b := a + 1; b < n-2; b++ {
			for c := b + 1; c < n-1; c++ {
				for d := c + 1; d < n; d++ {
					if nums[a]+nums[b]+nums[c] == nums[d] {
						ans++
					}
				}
			}
		}
	}
	return ans
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Naive Brute Force Approach

Time Complexity: O(n^4)
Space Complexity: O(1).

Optimized Hash Map Approach

Time Complexity: O(n^3).
Space Complexity: O(n) for dictionary maintenance.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Naive Brute Force EnumerationO(n^4)O(1)Best for understanding the constraint a < b < c < d or when input size is very small.
Hash Map OptimizationO(n^2)O(n)Preferred solution in interviews and large inputs; reduces nested loops using constant‑time hash lookups.

Frequently asked questions

Is Count Special Quadruplets easy or hard?

Count Special Quadruplets is classified as an Easy problem on LeetCode. The brute force solution is straightforward, but recognizing the equation transformation and applying a hash map to reach O(n^2) efficiency demonstrates stronger problem‑solving skills.

Count Special Quadruplets Python/Java solution

Python and Java implementations typically use a dictionary or HashMap to store differences between elements while iterating from the right side of the array. The algorithm checks pair sums on the left and adds the frequency of matching differences, resulting in an O(n^2) solution.

How to solve Count Special Quadruplets in O(n^2)?

Rearrange the equation to nums[a] + nums[b] = nums[d] - nums[c]. While iterating from the right side of the array, store the differences (nums[d] - nums[c]) in a hash map. Then iterate pairs (a, b) on the left and check whether their sum exists in the map, accumulating the frequency of matches.

What is the best approach for Count Special Quadruplets?

The most efficient approach uses a hash map to store differences between elements on the right side of the array. By transforming the equation nums[a] + nums[b] + nums[c] = nums[d] into nums[a] + nums[b] = nums[d] - nums[c], the algorithm reduces the search to pair sums and hash lookups. This achieves about O(n^2) time with O(n) extra space.

Is Count Special Quadruplets asked at Google/Amazon/Meta?

Count Special Quadruplets is a common array and hash‑table interview pattern seen in coding interviews. While the exact problem may not appear frequently at top companies, similar variations involving pair sums, hash maps, and index constraints appear in interviews at companies like Amazon, Google, and Meta.

What data structure is used in Count Special Quadruplets?

The optimized solution relies on a hash map (dictionary) to store frequencies of value differences such as nums[d] - nums[c]. This allows constant‑time lookups when checking whether a pair sum nums[a] + nums[b] completes the equation.

What is the time complexity of Count Special Quadruplets?

The naive enumeration solution runs in O(n^4) time because it checks every quadruplet combination. With a hash map optimization that stores differences for (c, d) pairs and matches them against sums of (a, b), the complexity improves to O(n^2) time and O(n) space.

Comments

Now write it yourselfClose this page and solve Count Special Quadruplets in the editor, without looking.
Practise Count Special Quadruplets