Given an array arr[] of size N and an integer S, the task is to find the count of quadruplets present in the given array having sum S.
Examples:
Input: arr[] = {1, 5, 3, 1, 2, 10}, S = 20
Output: 1
Explanation: Only quadruplet satisfying the conditions is arr[1] + arr[2] + arr[4] + arr[5] = 5 + 3 + 2 + 10 = 20.
Input: N = 6, S = 13, arr[] = {4, 5, 3, 1, 2, 4}
Output: 3
Explanation: Three quadruplets with sum 13 are:
- arr[0] + arr[2] + arr[4] + arr[5] = 4 + 3 + 2 + 4 = 13
- arr[0] + arr[1] + arr[2] + arr[3] = 4 + 5 + 3 + 1 = 13
- arr[1] + arr[2] + arr[3] + arr[5] = 5 + 3 + 1 + 4 = 13
Naive Approach: The idea is to generate all possible combinations of length 4 from the given array. For each quadruplet, if the sum equals S, then increment the counter by 1. After checking all the quadruplets, print the counter as the total number of quadruplets having sum S.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countSum( int a[], int n, int sum)
{
int i, j, k, l;
int count = 0;
for (i = 0; i < n - 3; i++) {
for (j = i + 1; j < n - 2; j++) {
for (k = j + 1; k < n - 1; k++) {
for (l = k + 1; l < n; l++) {
if (a[i] + a[j]
+ a[k] + a[l]
== sum)
count++;
}
}
}
}
return count;
}
int main()
{
int arr[] = { 4, 5, 3, 1, 2, 4 };
int S = 13;
int N = sizeof (arr) / sizeof (arr[0]);
cout << countSum(arr, N, S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSum( int a[], int n, int sum)
{
int i, j, k, l;
int count = 0 ;
for (i = 0 ; i < n - 3 ; i++)
{
for (j = i + 1 ; j < n - 2 ; j++)
{
for (k = j + 1 ; k < n - 1 ; k++)
{
for (l = k + 1 ; l < n; l++)
{
if (a[i] + a[j] +
a[k] + a[l] == sum)
count++;
}
}
}
}
return count;
}
public static void main(String args[])
{
int arr[] = { 4 , 5 , 3 , 1 , 2 , 4 };
int S = 13 ;
int N = arr.length;
System.out.print(countSum(arr, N, S));
}
}
|
Python3
def countSum(a, n, sum ):
count = 0
for i in range (n - 3 ):
for j in range (i + 1 , n - 2 ):
for k in range (j + 1 , n - 1 ):
for l in range (k + 1 , n):
if (a[i] + a[j] + a[k] + a[l] = = sum ):
count + = 1
return count
if __name__ = = '__main__' :
arr = [ 4 , 5 , 3 , 1 , 2 , 4 ]
S = 13
N = len (arr)
print (countSum(arr, N, S))
|
C#
class GFG{
static int countSum( int []a, int n, int sum)
{
int i, j, k, l;
int count = 0;
for (i = 0; i < n - 3; i++)
{
for (j = i + 1; j < n - 2; j++)
{
for (k = j + 1; k < n - 1; k++)
{
for (l = k + 1; l < n; l++)
{
if (a[i] + a[j] +
a[k] + a[l] == sum)
count++;
}
}
}
}
return count;
}
public static void Main()
{
int []arr = { 4, 5, 3, 1, 2, 4 };
int S = 13;
int N = arr.Length;
System.Console.Write(countSum(arr, N, S));
}
}
|
Javascript
<script>
function countSum(a, n, sum)
{
let i, j, k, l;
let count = 0;
for (i = 0; i < n - 3; i++)
{
for (j = i + 1; j < n - 2; j++)
{
for (k = j + 1; k < n - 1; k++)
{
for (l = k + 1; l < n; l++)
{
if (a[i] + a[j] +
a[k] + a[l] == sum)
count++;
}
}
}
}
return count;
}
let arr = [ 4, 5, 3, 1, 2, 4 ];
let S = 13;
let N = arr.length;
document.write(countSum(arr, N, S));
</script>
|
Output:
3
Time Complexity: O(N4)
Auxiliary Space: O(1)
Better Approach: To optimize the above approach, the idea is to use a Map data structure. Follow the steps below to solve the problem:
- Initialize the counter count with 0 to store the number of quadruplets.
- Traverse the given array over the range [0, N – 3)using the variable i. For each element arr[i], traverse the array again over the range [i + 1, N – 2) using the variable j and do the following:
- Find the value of the required sum(say req) as (S – arr[i] – arr[j]).
- Initialize the count_twice with 0 that will store the count of ordered pairs in the above subarray with sum (S – arr[i] – arr[j]).
- After finding the count_twice, update the count by count_twice / 2.
- After the above steps, print the value of count as the result.
Below is the implementation of the above idea:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int countSum( int a[], int n, int sum)
{
int i, j, k, l;
int count = 0;
for (i = 0; i < n - 3; i++) {
for (j = i + 1; j < n - 2; j++) {
int req = sum - a[i] - a[j];
unordered_map< int , int > m;
for (k = j + 1; k < n; k++)
m[a[k]]++;
int twice_count = 0;
for (k = j + 1; k < n; k++) {
twice_count += m[req - a[k]];
if (req - a[k] == a[k])
twice_count--;
}
count += twice_count / 2;
}
}
return count;
}
int main()
{
int arr[] = { 4, 5, 3, 1, 2, 4 };
int S = 13;
int N = sizeof (arr) / sizeof (arr[0]);
cout << countSum(arr, N, S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSum( int a[], int n, int sum)
{
int i, j, k, l;
int count = 0 ;
for (i = 0 ; i < n - 3 ; i++)
{
for (j = i + 1 ; j < n - 2 ; j++)
{
int req = sum - a[i] - a[j];
HashMap<Integer, Integer> m = new HashMap<>();
for (k = j + 1 ; k < n; k++)
if (m.containsKey(a[k]))
{
m.put(a[k], m.get(a[k]) + 1 );
}
else
{
m.put(a[k], 1 );
}
int twice_count = 0 ;
for (k = j + 1 ; k < n; k++)
{
if (m.containsKey(req - a[k]))
twice_count += m.get(req - a[k]);
if (req - a[k] == a[k])
twice_count--;
}
count += twice_count / 2 ;
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 4 , 5 , 3 , 1 , 2 , 4 };
int S = 13 ;
int N = arr.length;
System.out.print(countSum(arr, N, S));
}
}
|
Python3
def countSum(a, n, sum ):
count = 0
for i in range (n - 3 ):
for j in range (i + 1 , n - 2 , 1 ):
req = sum - a[i] - a[j]
m = {}
for k in range (j + 1 , n, 1 ):
m[a[k]] = m.get(a[k], 0 ) + 1
twice_count = 0
for k in range (j + 1 , n, 1 ):
twice_count + = m.get(req - a[k], 0 )
if (req - a[k] = = a[k]):
twice_count - = 1
count + = twice_count / / 2
return count
if __name__ = = '__main__' :
arr = [ 4 , 5 , 3 , 1 , 2 , 4 ]
S = 13
N = len (arr)
print (countSum(arr, N, S))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countSum( int []a, int n,
int sum)
{
int i, j, k;
int count = 0;
for (i = 0; i < n - 3; i++)
{
for (j = i + 1; j < n - 2; j++)
{
int req = sum - a[i] - a[j];
Dictionary< int ,
int > m = new Dictionary< int ,
int >();
for (k = j + 1; k < n; k++)
if (m.ContainsKey(a[k]))
{
m[a[k]]++;
}
else
{
m.Add(a[k], 1);
}
int twice_count = 0;
for (k = j + 1; k < n; k++)
{
if (m.ContainsKey(req - a[k]))
twice_count += m[req - a[k]];
if (req - a[k] == a[k])
twice_count--;
}
count += twice_count / 2;
}
}
return count;
}
public static void Main(String[] args)
{
int []arr = { 4, 5, 3, 1, 2, 4 };
int S = 13;
int N = arr.Length;
Console.Write(countSum(arr, N, S));
}
}
|
Javascript
<script>
function countSum(a, n, sum)
{
var i, j, k, l;
var count = 0;
for (i = 0; i < n - 3; i++) {
for (j = i + 1; j < n - 2; j++) {
var req = sum - a[i] - a[j];
var m = new Map();
for (k = j + 1; k < n; k++)
{
if (m.has(a[k]))
m.set(a[k], m.get(a[k])+1)
else
m.set(a[k], 1)
}
var twice_count = 0;
for (k = j + 1; k < n; k++) {
if (m.has(req - a[k]))
twice_count += m.get(req - a[k]);
if ((req - a[k]) == a[k])
twice_count--;
}
count += parseInt(twice_count / 2);
}
}
return count;
}
var arr = [4, 5, 3, 1, 2, 4];
var S = 13;
var N = arr.length;
document.write( countSum(arr, N, S));
</script>
|
Output:
3
Time complexity: O(N3) where N is the size of the given array,
Auxiliary Space: O(N)
Efficient Approach: The idea is similar to the above approach using a map. In this approach, fix the 3rd element, then find and store the frequency of sums of all possible first two elements of any quadruplet of the given array. Follow the below steps to solve the problem:
- Initialize the counter count to store the total quadruplets with the given sum S and a map to store all possible sums for the first two elements of each possible quadruplet.
- Traverse the given array over the range [0, N – 1] using the variable i where arr[i] is the fixed 3rd element.
- Then for each element arr[i] in the above step, traverse the given array over the range [i + 1, N – 1] using the variable j and increment the counter count by map[arr[i] + arr[j]].
- After traversing from the above loop, for each element arr[i], traverse the array arr[] from j = 0 to i – 1 and increment the frequency of any sum arr[i] + arr[j] of the first two elements of any possible quadruplet by 1 i.e., increment map[arr[i] + arr[j]] by 1.
- Repeat the above steps for each element arr[i] and then print the counter count as the total number of quadruplets with the given sum S.
Below is the implementation of the above idea:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int countSum( int a[], int n, int sum)
{
int i, j, k;
int count = 0;
unordered_map< int , int > m;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
int temp = a[i] + a[j];
if (temp < sum)
count += m[sum - temp];
}
for (j = 0; j < i; j++) {
int temp = a[i] + a[j];
if (temp < sum)
m[temp]++;
}
}
return count;
}
int main()
{
int arr[] = { 4, 5, 3, 1, 2, 4 };
int S = 13;
int N = sizeof (arr) / sizeof (arr[0]);
cout << countSum(arr, N, S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSum( int a[], int n, int sum)
{
int i, j, k;
int count = 0 ;
HashMap<Integer, Integer> m = new HashMap<>();
for (i = 0 ; i < n - 1 ; i++)
{
for (j = i + 1 ; j < n; j++)
{
int temp = a[i] + a[j];
if (temp < sum && m.containsKey(sum - temp))
count += m.get(sum - temp);
}
for (j = 0 ; j < i; j++)
{
int temp = a[i] + a[j];
if (temp < sum)
if (m.containsKey(temp))
m.put(temp, m.get(temp) + 1 );
else
m.put(temp, 1 );
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 4 , 5 , 3 , 1 , 2 , 4 };
int S = 13 ;
int N = arr.length;
System.out.print(countSum(arr, N, S));
}
}
|
Python3
from collections import defaultdict
def countSum(a, n, sum ):
count = 0
m = defaultdict( int )
for i in range (n - 1 ):
for j in range (i + 1 , n):
temp = a[i] + a[j]
if (temp < sum ):
count + = m[ sum - temp]
for j in range (i):
temp = a[i] + a[j]
if (temp < sum ):
m[temp] + = 1
return count
if __name__ = = "__main__" :
arr = [ 4 , 5 , 3 , 1 , 2 , 4 ]
S = 13
N = len (arr)
print (countSum(arr, N, S))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countSum( int []a, int n, int sum)
{
int i, j;
int count = 0;
Dictionary< int ,
int > m = new Dictionary< int ,
int >();
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
int temp = a[i] + a[j];
if (temp < sum && m.ContainsKey(sum - temp))
count += m[sum - temp];
}
for (j = 0; j < i; j++)
{
int temp = a[i] + a[j];
if (temp < sum)
if (m.ContainsKey(temp))
m[temp]++;
else
m.Add(temp, 1);
}
}
return count;
}
public static void Main(String[] args)
{
int []arr = { 4, 5, 3, 1, 2, 4 };
int S = 13;
int N = arr.Length;
Console.Write(countSum(arr, N, S));
}
}
|
Javascript
<script>
function countSum(a, n, sum)
{
let i, j, k;
let count = 0;
let m = new Map();
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
let temp = a[i] + a[j];
if (temp < sum && m.has(sum - temp))
count += m.get(sum - temp);
}
for (j = 0; j < i; j++)
{
let temp = a[i] + a[j];
if (temp < sum)
if (m.has(temp))
m.set(temp, m.get(temp) + 1);
else
m.set(temp, 1);
}
}
return count;
}
let arr = [ 4, 5, 3, 1, 2, 4 ];
let S = 13;
let N = arr.length;
document.write(countSum(arr, N, S));
</script>
|
Output:
3
Time Complexity: O(N2)
Auxiliary Space: O(N)