Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Hashing & Two Pointers

Count Distinct Quadruplets with Target Sum

Medium · Hashing & Two Pointers · Asked at Amazon, Google, Microsoft, Adobe

Count the distinct quadruplets of values [a, b, c, d] with a ≤ b ≤ c ≤ d that can be taken from four different positions of the array and satisfy a + b + c + d = target. Two quadruplets are the same if they have the same four values.

Input

First line: n. Second line: n space-separated integers. Third line: target.

Output

The number of distinct quadruplets.

Constraints

Sort the array. Fix the first two values with two loops (skipping repeated values), then find the last two with two pointers, again skipping repeats after a match. O(n³). Sums can pass 2^31 — use 64-bit integers.

Example 1

Input

6
1 0 -1 0 -2 2
0

Output

3

Example 2

Input

5
2 2 2 2 2
8

Output

1

Hints

  1. Sort first — it makes duplicates adjacent and enables two pointers.
  2. Fix the first two values with two loops; find the last two with a left and a right pointer.
  3. Skip a value equal to the previous one at every level so each quadruplet is counted once.

Approach

After sorting, loop i over distinct first values and j > i over distinct second values. With lo = j + 1 and hi = n − 1, compare the sum to the target: move lo up if small, hi down if large. On a match, count it and move lo past all equal values and hi past all equal values. Sums of four values reach 4 × 10^9, so compute them in 64 bits — 32-bit overflow would create fake matches.

Complexity: O(n³) time · O(1) extra space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<long long> a(n);
    for (auto &x : a) cin >> x;
    long long T;
    cin >> T;
    sort(a.begin(), a.end());
    long long count = 0;
    for (int i = 0; i < n; i++) {
        if (i && a[i] == a[i - 1]) continue;
        for (int j = i + 1; j < n; j++) {
            if (j > i + 1 && a[j] == a[j - 1]) continue;
            int lo = j + 1, hi = n - 1;
            while (lo < hi) {
                long long sum = a[i] + a[j] + a[lo] + a[hi];
                if (sum < T) lo++;
                else if (sum > T) hi--;
                else {
                    count++;
                    long long lv = a[lo], hv = a[hi];
                    while (lo < hi && a[lo] == lv) lo++;
                    while (lo < hi && a[hi] == hv) hi--;
                }
            }
        }
    }
    cout << count << "\n";
    return 0;
}

Python solution

import sys

data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = sorted(data[1 : 1 + n])
T = data[1 + n]
count = 0
for i in range(n):
    if i and a[i] == a[i - 1]:
        continue
    for j in range(i + 1, n):
        if j > i + 1 and a[j] == a[j - 1]:
            continue
        lo, hi = j + 1, n - 1
        base = a[i] + a[j]
        while lo < hi:
            s = base + a[lo] + a[hi]
            if s < T:
                lo += 1
            elif s > T:
                hi -= 1
            else:
                count += 1
                lv, hv = a[lo], a[hi]
                while lo < hi and a[lo] == lv:
                    lo += 1
                while lo < hi and a[hi] == hv:
                    hi -= 1
print(count)

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int n = (int) in.nval;
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            in.nextToken();
            a[i] = (long) in.nval;
        }
        in.nextToken();
        long T = (long) in.nval;
        Arrays.sort(a);
        long count = 0;
        for (int i = 0; i < n; i++) {
            if (i > 0 && a[i] == a[i - 1]) continue;
            for (int j = i + 1; j < n; j++) {
                if (j > i + 1 && a[j] == a[j - 1]) continue;
                int lo = j + 1, hi = n - 1;
                while (lo < hi) {
                    long sum = a[i] + a[j] + a[lo] + a[hi];
                    if (sum < T) lo++;
                    else if (sum > T) hi--;
                    else {
                        count++;
                        long lv = a[lo], hv = a[hi];
                        while (lo < hi && a[lo] == lv) lo++;
                        while (lo < hi && a[hi] == hv) hi--;
                    }
                }
            }
        }
        System.out.println(count);
    }
}

Solve Count Distinct Quadruplets with Target Sum online · All practice problems