DDSA Solutions

1995. Count Special Quadruplets

Time: O(n²)
Space: O(n)

Problem Overview

Count Special Quadruplets (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Hash Table pattern in coding interviews. Two-loop with HashMap tracking nums[d]-nums[c] values; count matching a+b+c == d.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Two-loop with HashMap tracking nums[d]-nums[c] values; count matching a+b+c == d.

Related patterns: Array, Hash Table, enumeration

1995.cs
C#
// Approach: Two-loop with HashMap tracking nums[d]-nums[c] values; count matching a+b+c == d.
// Time: O(n²) Space: O(n)

public class Solution
{
    public int CountQuadruplets(int[] nums)
    {
        int n = nums.Length;
        int ans = 0;
        Dictionary<int, int> count = new Dictionary<int, int>();

        // nums[a] + nums[b] + nums[c] == nums[d]
        // => nums[a] + nums[b] == nums[d] - nums[c]
        for (int b = n - 1; b > 0; --b)
        { // `b` also represents `c`.
            for (int a = b - 1; a >= 0; --a)
                ans += count.TryGetValue(nums[a] + nums[b], out int value) ? value : 0;
            for (int d = n - 1; d > b; --d)
                if (count.ContainsKey(nums[d] - nums[b]))
                {
                    count[nums[d] - nums[b]]++;
                }
                else
                {
                    count[nums[d] - nums[b]] = 1;
                } // b := c
        }

        return ans;
    }
}
Was this solution helpful?

Related Problems