Check if all possible Triplet Sum is present in given Array
Last Updated :
11 Oct, 2022
Given an array arr[] of size N, the task is to check if for all distinct triplets of indices i, j, k, [ 0 ≤ i < j < k ≤ N-1 ] the sum arr[i]+arr[j]+arr[k] is present in the array.
Examples:
Input: arr[] = {-1, 0, 0, 1}
Output: True
Explanation: For index 0, 1, 2: arr[i]+arr[j]+arr[k] = -1 + 0 + 0 = -1
For index 0, 1, 3: arr[i]+arr[j]+arr[k] = -1 + 0 + 1 = 0
For index 0, 2, 3: arr[i]+arr[j]+arr[k] = -1 + 0 + 1 = 0
For index 1, 2, 3: arr[i]+arr[j]+arr[k] = 0 + 0 + 1 = 1
-1, 0, 1 all are elements of the array arr[], so, the condition holds true.
Input: arr[] = {0, 0, 0}
Output: True
Approach: The problem can be solved using the following mathematical idea:
If there are more than or equal to 3 positive elements or more than or equal to 3 negative elements, then the condition arr[i]+arr[j]+arr[k] = an element of the array cannot be true.
Otherwise, push all the element of the array in a linear data structure like vector and if there are more than one zero in the array then push only one 0 in the vector, the vector will contain atmost 5 elements i.e., 2 positives, 2 negatives and 1 zero.
Now, push all elements into a set for checking the condition, and apply bruteforce because there are only 5 elements atmost in the array. For checking the condition of the question, check if v[i]+v[j]+v[k] is present in the set or not for all the triplets from the vector.
Follow the steps mentioned below to implement the observation:
- Initialize variables (say CP = 0, and CN = 0) for counting positives and negatives respectively.
- Run a loop and push all the elements of the array in the vector.
- If CP > 2 or CN < 2 at any point of time then the given condition cannot be satisfied. So return false.
- Push only one 0 if there are at least one 0 into the vector.
- Now apply three nested loops and find if the condition holds true or not.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the condition is true or not
bool solve(int* arr, int n)
{
// Initialize the variables
int CP = 0, CN = 0;
vector<int> v;
bool f = 1;
// Count the number of positives and negatives
// in the original array and put it into vector
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
v.push_back(arr[i]);
CP++;
}
else if (arr[i] < 0) {
v.push_back(arr[i]);
CN++;
}
else {
if (f)
v.push_back(arr[i]);
f = 0;
}
if (CP > 2 || CN > 2)
break;
}
// If there are more than 2 positives or
// 2 negatives then return 0
if (CP > 2 || CN > 2)
return 0;
// Else case
else {
// Put elements of vector into the set
set<int> s;
for (int i = 0; i < v.size(); i++) {
s.insert(v[i]);
}
// Check the condition for every index
for (int i = 0; i < v.size(); i++) {
for (int j = i + 1; j < v.size(); j++) {
for (int k = j + 1; k < v.size(); k++) {
// If element is not present
// then the pointer
// points to s.end()
if (s.find(v[i] + v[j] + v[k])
== s.end()) {
return 0;
}
}
}
}
// The condition is true for all indexes
// so, return 1
return 1;
}
}
// Driver Code
int main()
{
int arr[] = { -1, 0, 0, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
if (solve(arr, N))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
Java
// Java code to implement the above approach
import java.util.*;
class GFG{
// Function to find the condition is true or not
static boolean solve(int[] arr, int n)
{
// Initialize the variables
int CP = 0, CN = 0;
Vector<Integer> v = new Vector<>();
boolean f = true;
// Count the number of positives and negatives
// in the original array and put it into vector
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
v.add(arr[i]);
CP++;
}
else if (arr[i] < 0) {
v.add(arr[i]);
CN++;
}
else {
if (f)
v.add(arr[i]);
f = false;
}
if (CP > 2 || CN > 2)
break;
}
// If there are more than 2 positives or
// 2 negatives then return 0
if (CP > 2 || CN > 2)
return false;
// Else case
else {
// Put elements of vector into the set
HashSet<Integer> s = new HashSet<>();
for (int i = 0; i < v.size(); i++) {
s.add(v.get(i));
}
// Check the condition for every index
for (int i = 0; i < v.size(); i++) {
for (int j = i + 1; j < v.size(); j++) {
for (int k = j + 1; k < v.size(); k++) {
// If element is not present
// then the pointer
// points to s.end()
if (!s.contains(v.get(i) + v.get(j) + v.get(k))) {
return false;
}
}
}
}
// The condition is true for all indexes
// so, return 1
return true;
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { -1, 0, 0, 1 };
int N = arr.length;
if (solve(arr, N))
System.out.print("True" +"\n");
else
System.out.print("False" +"\n");
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 code to implement the above approach
def solve(arr, n):
# Initialize the variables
CP = 0
CN = 0
v = []
f = True
# Count the number of positives and negatives
# in the original array and put it into array
for i in range(n):
if(arr[i] > 0):
v.append(arr[i])
CP += 1
elif(arr[i] < 0):
v.append(arr[i])
CN += 1
else:
if(f):
v.append(arr[i])
f = False
if(CP > 2 or CN > 2):
break
# If there are more than 2 positives or 2 negatives then return 0
if(CP > 2 or CN > 2):
return False
# Else case
else:
# Put element of array into the set
s = set()
for i in range(len(v)):
s.add(v[i])
# Check the condition for every index
for i in range(len(v)):
for j in range(i+1, len(v), 1):
for k in range(j+1, len(v), 1):
# If element is not present then the pointer points to s
if((v[i]+v[j]+v[k]) not in s):
return False
return True
arr = [-1, 0, 0, 1]
N = len(arr)
if(solve(arr, N)):
print("True")
else:
print("False")
# This code is contributed by lokeshmvs21.
C#
// C# code to implement the above approach
using System;
using System.Collections.Generic;
public class GFG{
// Function to find the condition is true or not
static bool solve(int[] arr, int n)
{
// Initialize the variables
int CP = 0, CN = 0;
List<int> v = new List<int>();
bool f = true;
// Count the number of positives and negatives
// in the original array and put it into vector
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
v.Add(arr[i]);
CP++;
}
else if (arr[i] < 0) {
v.Add(arr[i]);
CN++;
}
else {
if (f)
v.Add(arr[i]);
f = false;
}
if (CP > 2 || CN > 2)
break;
}
// If there are more than 2 positives or
// 2 negatives then return 0
if (CP > 2 || CN > 2)
return false;
// Else case
else {
// Put elements of vector into the set
HashSet<int> s = new HashSet<int>();
for (int i = 0; i < v.Count; i++) {
s.Add(v[i]);
}
// Check the condition for every index
for (int i = 0; i < v.Count; i++) {
for (int j = i + 1; j < v.Count; j++) {
for (int k = j + 1; k < v.Count; k++) {
// If element is not present
// then the pointer
// points to s.end()
if (!s.Contains(v[i] + v[j] + v[k])) {
return false;
}
}
}
}
// The condition is true for all indexes
// so, return 1
return true;
}
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { -1, 0, 0, 1 };
int N = arr.Length;
if (solve(arr, N))
Console.Write("True" +"\n");
else
Console.Write("False" +"\n");
}
}
// This code contributed by shikhasingrajput
JavaScript
<script>
// JavaScript code to implement the above approach
// Function to find the condition is true or not
const solve = (arr, n) => {
// Initialize the variables
let CP = 0, CN = 0;
let v = [];
let f = 1;
// Count the number of positives and negatives
// in the original array and put it into vector
for (let i = 0; i < n; i++) {
if (arr[i] > 0) {
v.push(arr[i]);
CP++;
}
else if (arr[i] < 0) {
v.push(arr[i]);
CN++;
}
else {
if (f)
v.push(arr[i]);
f = 0;
}
if (CP > 2 || CN > 2)
break;
}
// If there are more than 2 positives or
// 2 negatives then return 0
if (CP > 2 || CN > 2)
return 0;
// Else case
else {
// Put elements of vector into the set
let s = new Set();
for (let i = 0; i < v.length; i++) {
s.add(v[i]);
}
// Check the condition for every index
for (let i = 0; i < v.length; i++) {
for (let j = i + 1; j < v.length; j++) {
for (let k = j + 1; k < v.length; k++) {
// If element is not present
// then the pointer
// points to s.end()
if (!s.has(v[i] + v[j] + v[k])) {
return 0;
}
}
}
}
// The condition is true for all indexes
// so, return 1
return 1;
}
}
// Driver Code
let arr = [-1, 0, 0, 1];
let N = arr.length;
if (solve(arr, N))
document.write("True<br/>");
else
document.write("False<br/>");
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
- The frequency count takes O(N) time
- The final vector can have at most 5 elements, So 3 nested loops will take at most O(1) time
Auxiliary Space: O(1)
Similar Reads
3 Sum - Count Triplets With Given Sum In Sorted Array Given a sorted array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. More specifically, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k.Examp
10 min read
4 Sum - Check if a Quadruple with given Sum Exists in an Array Given an array of integers, check if there are four elements in the array with given sum.Example:Input: arr = {10, 20, 30, 40, 1, 2}, target = 91 Output: TrueExplanation: Sum of 20 + 30 + 40 + 1 = 91Input: arr = {1, 2, 3, 4, 5, 9, 7, 8}, target = 16 Output: TrueExplanation: Sum of output is equal to
14 min read
Check if is possible to get given sum from a given set of elements Given array of numbers and a integer x. Find whether it is possible or not to get x by adding elements of given array, we may pick a single element multiple times. For a given array, there can be many sum queries. Examples: Input : arr[] = { 2, 3} q[] = {8, 7} Output : Yes Yes Explanation : 2 + 2 +
7 min read
3 Sum â All Distinct Triplets with given Sum in an Array Given an array arr[], and an integer target, find all possible unique triplets in the array whose sum is equal to the given target value. We can return triplets in any order, but all the returned triplets should be internally sorted, i.e., for any triplet [q1, q2, q3], the condition q1 ⤠q2 ⤠q3 sho
15+ min read
Subset array sum by generating all the subsets Given an array of size N and a sum, the task is to check whether some array elements can be added to sum to N . Note: At least one element should be included to form the sum.(i.e. sum cant be zero) Examples: Input: array = -1, 2, 4, 121, N = 5 Output: YES The array elements 2, 4, -1 can be added to
5 min read
3 Sum - Pythagorean Triplet in an array Given an array of positive integers, the task is to determine if a Pythagorean triplet exists in the given array. A triplet {a, b, c} is considered a Pythagorean triplet if it satisfies the condition a2 + b2 = c2.Example:Input: arr[] = [3, 1, 4, 6, 5] Output: trueExplanation: The array contains a Py
15+ min read
Sum of special triplets having elements from 3 arrays Given three arrays A, B, and C, the task is to find sum of values of all special triplets. A special triplet is defined as a triplet (X, Y, Z) where the condition : X ? Y and Z ? Y always hold true. The value of each triplet (X, Y, Z) is given by: f(X, Y, Z) = (X + Y) * (Y + Z) Note: If a triplet is
15+ min read
Check if there exist 4 indices in the array satisfying the given condition Given an array A[] of N positive integers and 3 integers X, Y, and Z, the task is to check if there exist 4 indices (say p, q, r, s) such that the following conditions are satisfied: 0 < p < q < r < s < NSum of the subarray from A[p] to A[q - 1] is XSum of the subarray from A[q] to A[
8 min read
Count number of triplets in an array having sum in the range [a, b] Given an array of distinct integers and a range [a, b], the task is to count the number of triplets having a sum in the range [a, b].Examples: Input : arr[] = {8, 3, 5, 2} range = [7, 11] Output : 1 There is only one triplet {2, 3, 5} having sum 10 in range [7, 11]. Input : arr[] = {2, 7, 5, 3, 8, 4
15+ min read
4 Sum - All Distinct Quadruplets with given Sum in an Array Given an array arr[], and an integer target, find all possible unique quadruplets in an array whose sum is equal to the given target value. We can return quadruplets in any order, but all the quadruplets should be internally sorted, i.e., for any quadruplets [q1, q2, q3, q4] the following should fol
15+ min read