leetcode

Count Special Quadruplets - Link

Question Description

You are 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.


Constraints


Approach

We need to count all ordered quadruplets (a, b, c, d) where nums[a] + nums[b] + nums[c] == nums[d] and a < b < c < d.

Brute force solution:

Optimization:


Dry Run

Example Input: nums = [1,2,3,6]

Step-by-step execution:

Final Answer = 1


Solution

class Solution {
    public int countQuadruplets(int[] nums) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                for (int k = j + 1; k < nums.length; k++) {
                    int sum = nums[i] + nums[j] + nums[k];
                    // small pruning: since nums[d] ≤ 100, skip if sum > 100
                    if (sum > 100) continue; 
                    for (int l = k + 1; l < nums.length; l++) {
                        if (sum == nums[l]) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }
}

Time and Space Complexity