The Wayback Machine - https://web.archive.org/web/20241009194534/https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/
Open In App

3 Sum – Find All Triplets with Zero Sum

Last Updated : 09 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[], the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to zero and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted order, i.e., i < j < k.

Examples :

Input: arr[] = {0, -1, 2, -3, 1}
Output: {{0, 1, 4}, {2, 3, 4}}
Explanation:  Two triplets with sum 0 are:
arr[0] + arr[1] + arr[4] = 0 + (-1) + 1 = 0
arr[2] + arr[3] + arr[4] = 2 + (-3) + 1 = 0

Input: arr[] = {1, -2, 1, 0, 5}
Output: {{0, 1, 2}}
Explanation: Only triplet which satisfies the condition is arr[0] + arr[1] + arr[2] = 1 + (-2) + 1 = 0

Input: arr[] = {2, 3, 1, 0, 5}
Output: {{}}
Explanation: There is no triplet with sum 0

[Naive Approach] Using Three Nested Loops – O(n^3) Time and O(1) Space

The simplest approach is to generate all possible triplets using three nested loops and if the sum of any triplet is equal to zero then add it to the result. 

C++
// C++ program to find triplet having sum zero using
// three nested loops

#include <iostream>
#include <vector>
using namespace std;

vector<vector<int>> findTriplets(vector<int> &arr) {
    vector<vector<int>> res; 
    int n = arr.size(); 

    // Generating all triplets
    for (int i = 0; i < n - 2; i++) {
        for (int j = i + 1; j < n - 1; j++) {
            for (int k = j + 1; k < n; k++) {

                // If the sum of a triplet equals to zero
                  // then add it's indices to the result
                if (arr[i] + arr[j] + arr[k] == 0) 
                    res.push_back({i, j, k});
            }
        }
    }
    return res; 
}

int main() {
    vector<int> arr = {0, -1, 2, -3, 1};
    vector<vector<int>> res = findTriplets(arr);
    for(int i = 0; i < res.size(); i++)
        cout << res[i][0] << " " << res[i][1] << " " << res[i][2] << endl;
  
    return 0;
}
C
// C program to find triplet having sum zero using 
// three nested loops
#include <stdio.h>
#include <stdlib.h>

#define MAX_LIMIT 100 

void findTriplets(int arr[], int n, int res[][3], int* count) {
    *count = 0; 

    // Generating all triplets
    for (int i = 0; i < n - 2; i++) {
        for (int j = i + 1; j < n - 1; j++) {
            for (int k = j + 1; k < n; k++) {
              
                // If the sum of triplet equals zero
                  // then add it's indexes to reuslt
                if (arr[i] + arr[j] + arr[k] == 0) {
                    res[*count][0] = i;
                    res[*count][1] = j;
                    res[*count][2] = k;
                    (*count)++; 
                }
            }
        }
    }
}

int main() {
    int arr[] = {0, -1, 2, -3, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
      
      // res array to store all triplets
    int res[MAX_LIMIT][3]; 
      
      // Variable to store number of triplets found
    int count = 0; 
    findTriplets(arr, n, res, &count);
    for (int i = 0; i < count; i++) 
        printf("%d %d %d\n", res[i][0], res[i][1], res[i][2]);
    
    return 0;
}
Java
// Java program to find triplet having sum zero using 
// three nested loops

import java.util.ArrayList;
import java.util.List;

class GfG {
    static ArrayList<ArrayList<Integer>> findTriplets(int[] arr) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        int n = arr.length;

        // Generating all triplets
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                for (int k = j + 1; k < n; k++) {
                  
                    // If the sum of triplet equals to zero
                    // then add it's indexes to the result
                    if (arr[i] + arr[j] + arr[k] == 0) {
                        ArrayList<Integer> triplet = new ArrayList<>();
                        triplet.add(i);
                        triplet.add(j);
                        triplet.add(k);
                        res.add(triplet);
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {0, -1, 2, -3, 1};
        ArrayList<ArrayList<Integer>> res = findTriplets(arr);
        for (List<Integer> triplet : res) 
            System.out.println(triplet.get(0) + " " + triplet.get(1)
                                                 + " " + triplet.get(2));
    }
}
Python
# Python program to find triplet with sum zero
# using three nested loops

def findTriplets(arr):
    res = []
    n = len(arr)

    # Generating all triplets
    for i in range(n - 2):
        for j in range(i + 1, n - 1):
            for k in range(j + 1, n):
              
                # If the sum of triplet equals to zero
                # then add it's indexes to the result
                if arr[i] + arr[j] + arr[k] == 0:
                    res.append([i, j, k])
    return res

arr = [0, -1, 2, -3, 1]
res = findTriplets(arr)
for triplet in res:
    print(triplet[0], triplet[1], triplet[2])
C#
// C# program to find triplet with sum zero using 
// three nested loops

using System;
using System.Collections.Generic;

class GfG {
    static List<List<int>> FindTriplets(int[] arr) {
        List<List<int>> res = new List<List<int>>();
        int n = arr.Length;

        // Generating all triplets
        for (int i = 0; i < n - 2; i++) {
            for (int j = i + 1; j < n - 1; j++) {
                for (int k = j + 1; k < n; k++) {
                  
                    // If the sum of triplet equals to zero
                    // then add it's indexes to the result
                    if (arr[i] + arr[j] + arr[k] == 0) {
                        res.Add(new List<int> { i, j, k });
                    }
                }
            }
        }
        return res;
    }

    public static void Main() {
        int[] arr = { 0, -1, 2, -3, 1 };
        List<List<int>> res = FindTriplets(arr);
        foreach (var triplet in res) {
            Console.WriteLine($"{triplet[0]} {triplet[1]} {triplet[2]}");
        }
    }
}
JavaScript
// JavaScript program to find triplet with sum zero 
// using three nested loops

function findTriplets(arr) {
    const res = [];
    const n = arr.length;

    // Generating all triplets
    for (let i = 0; i < n - 2; i++) {
        for (let j = i + 1; j < n - 1; j++) {
            for (let k = j + 1; k < n; k++) {
            
                // If the sum of triplet equals to zero
                // then add it's indexes to the result
                if (arr[i] + arr[j] + arr[k] === 0) {
                    res.push([i, j, k]);
                }
            }
        }
    }
    return res;
}

const arr = [0, -1, 2, -3, 1];
const res = findTriplets(arr);
res.forEach(triplet => {
    console.log(triplet[0] + " " + triplet[1] + " " + triplet[2]);
});

Output
0 1 4
2 3 4

Time Complexity: O(n3), As three nested loops are used.
Auxiliary Space: O(1)

[Expected Approach] Using Hashing – O(n^2) Time and O(n^2) Space

The idea is to store sum of all the pairs with their indices the hash map. Then, for each element in the array, we check if the pair which makes triplet’s sum zero, exists in the hash map or not. Since there can be multiple valid pairs, we add each one to the hash set (to manage duplicates) while ensuring that all indices in the triplet are distinct.

C++
// C++ program to find all triplets with zero sum using hashing
#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> findTriplets(vector<int> &arr) {

    // Set to handle duplicates
    set<vector<int>> resSet;
    int n = arr.size();
    unordered_map<int, vector<pair<int, int>>> mp;

    // Store sum of all the pairs with their indices
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++)
            mp[arr[i] + arr[j]].push_back({i, j});
    }

      for (int i = 0; i < n; i++) {

        // Find remaining value to get zero sum
        int rem = -arr[i];
        if (mp.find(rem) != mp.end()) {
            vector<pair<int, int>> pairs = mp[rem];
            for (auto p : pairs) {
              
                  // Ensure no two indices are same in triplet
                if (p.first != i && p.second != i) {
                    vector<int> curr = {i, p.first, p.second};
                    sort(curr.begin(), curr.end());
                    resSet.insert(curr);
                }
            }
        }
    }

    vector<vector<int>> res(resSet.begin(), resSet.end());
    return res;
}

int main()
{
    vector<int> arr = {0, -1, 2, -3, 1};
    vector<vector<int>> res = findTriplets(arr);
    for (int i = 0; i < res.size(); i++)
        cout << res[i][0] << " " << res[i][1] << " " << res[i][2] << endl;

    return 0;
}
Java
// Java program to find all triplets with zero sum using hashing

import java.util.*;

class GfG {
    static ArrayList<ArrayList<Integer>> findTriplets(int[] arr) {
        
        // Set to handle duplicates
        Set<ArrayList<Integer>> resSet = new HashSet<>();
        int n = arr.length;
        Map<Integer, List<int[]>> mp = new HashMap<>();

        // Store sum of all the pairs with their indices
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                mp.computeIfAbsent(arr[i] + arr[j], 
                              k -> new ArrayList<>()).add(new int[]{i, j});
            }
        }

        for (int i = 0; i < n; i++) {
            
            // Find remaining value to get zero sum
            int rem = -arr[i];
            if (mp.containsKey(rem)) {
                List<int[]> pairs = mp.get(rem);
                for (int[] p : pairs) {
                    
                    // Ensure no two indices are same in triplet
                    if (p[0] != i && p[1] != i) {
                        ArrayList<Integer> curr = 
                          new ArrayList<>(Arrays.asList(i, p[0], p[1]));
                        Collections.sort(curr);
                        resSet.add(curr);
                    }
                }
            }
        }
        return new ArrayList<>(resSet);  
    }

    public static void main(String[] args) {
        int[] arr = {0, -1, 2, -3, 1};
        ArrayList<ArrayList<Integer>> res = findTriplets(arr);
        for (ArrayList<Integer> triplet : res) {
            System.out.println(triplet.get(0) + " " + 
                               triplet.get(1) + " " + triplet.get(2));
        }
    }
}
Python
# Python program to find all triplets with zero sum using hashing
def findTriplets(arr):

    # Set to handle duplicates
    resSet = set()
    n = len(arr)
    mp = {}

    # Store sum of all the pairs with their indices
    for i in range(n):
        for j in range(i + 1, n):
            s = arr[i] + arr[j]
            if s not in mp:
                mp[s] = []
            mp[s].append((i, j))

    for i in range(n):

        # Find remaining value to get zero sum
        rem = -arr[i]
        if rem in mp:
            for p in mp[rem]:
                
                # Ensure no two indices are the same in the triplet
                if p[0] != i and p[1] != i:
                    curr = sorted([i, p[0], p[1]])
                    resSet.add(tuple(curr))

    return [list(triplet) for triplet in resSet]

if __name__ == "__main__":
    arr = [0, -1, 2, -3, 1]
    res = findTriplets(arr)
    for triplet in res:
        print(triplet[0], triplet[1], triplet[2])
C#
// C# program to find all triplets with zero sum using hashing
using System;
using System.Collections.Generic;
using System.Linq; 

class GfG {
    public static List<List<int>> FindTriplets(int[] arr) {

        // Set to handle duplicates
        HashSet<List<int>> resSet = 
                          new HashSet<List<int>>(new ListComparer());
        int n = arr.Length;
        Dictionary<int, List<Tuple<int, int>>> mp = 
                          new Dictionary<int, List<Tuple<int, int>>>();

        // Store sum of all the pairs with their indices
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
                if (!mp.ContainsKey(sum)) {
                    mp[sum] = new List<Tuple<int, int>>();
                }
                mp[sum].Add(new Tuple<int, int>(i, j));
            }
        }

        for (int i = 0; i < n; i++) {
            int rem = -arr[i];
            if (mp.ContainsKey(rem)) {
                List<Tuple<int, int>> pairs = mp[rem];
                foreach (var p in pairs) {

                    // Ensure no two indices are the same in the triplet
                    if (p.Item1 != i && p.Item2 != i) {
                        List<int> curr = new List<int> 
                                        { i, p.Item1, p.Item2 };
                        curr.Sort();
                        resSet.Add(curr);
                    }
                }
            }
        }
        return new List<List<int>>(resSet);
    }

    static void Main() {
        int[] arr = { 0, -1, 2, -3, 1 };
        List<List<int>> res = FindTriplets(arr);

        foreach (var triplet in res) 
            Console.WriteLine($"{triplet[0]} {triplet[1]} {triplet[2]}");
    }

    public class ListComparer : IEqualityComparer<List<int>> {
        public bool Equals(List<int> x, List<int> y) {
            return x.SequenceEqual<int>(y);
        }

        public int GetHashCode(List<int> obj) {
            return string.Join(",", obj).GetHashCode();
        }
    }
}
JavaScript
// JavaScript program to find all triplets with zero sum using hashing
function findTriplets(arr) {

    // Set to handle duplicates
    let resSet = new Set();
    let n = arr.length;
    let mp = new Map();

    // Store sum of all the pairs with their indices
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            let sum = arr[i] + arr[j];
            if (!mp.has(sum)) {
                mp.set(sum, []);
            }
            mp.get(sum).push([i, j]);
        }
    }

    for (let i = 0; i < n; i++) {

        // Find remaining value to get zero sum
        let rem = -arr[i];
        if (mp.has(rem)) {
            let pairs = mp.get(rem);
            for (let p of pairs) {
              
                // Ensure no two indices are the same in the triplet
                if (p[0] != i && p[1] != i) {
                    let curr = [i, p[0], p[1]].sort((a, b) => a - b);
                    resSet.add(curr.join(","));
                }
            }
        }
    }
    return Array.from(resSet).map(triplet => 
                                    triplet.split(",").map(Number));
}

const arr = [0, -1, 2, -3, 1];
const ans = findTriplets(arr);
ans.forEach(triplet => {
    console.log(`${triplet[0]} ${triplet[1]} ${triplet[2]}`);
});

Output
0 1 4
2 3 4

Time Complexity: O(n2), Since two nested loops are used.
Auxiliary Space: O(n2), Since a HashMap is used to store all the pairs.

Please refer 3Sum – Complete Tutorial for all list of problems on triplets in an array.



Previous Article
Next Article

Similar Reads

Javascript Program to Find all triplets with zero sum
Given an array of distinct elements. The task is to find triplets in the array whose sum is zero. Examples : Input : arr[] = {0, -1, 2, -3, 1}Output : (0 -1 1), (2 -3 1)Explanation : The triplets with zero sum are0 + -1 + 1 = 0 and 2 + -3 + 1 = 0 Input : arr[] = {1, -2, 1, 0, 5}Output : 1 -2 1Explanation : The triplets with zero sum is1 + -2 + 1 =
6 min read
Remove all zero-rows and all zero-columns from a Matrix
Given a matrix arr[][] of size N * M, the task is to print the matrix after removing all rows and columns from the matrix which consists of 0s only. Examples: Input: arr[][] ={ { 1, 1, 0, 1 }, { 0, 0, 0, 0 }, { 1, 1, 0, 1}, { 0, 1, 0, 1 } } Output: 111 111 011 Explanation: Initially, the matrix is as follows: arr[][] = { { 1, 1, 0, 1 }, { 0, 0, 0,
15+ min read
Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15};Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} an
11 min read
Javascript Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15};Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} an
3 min read
Find sum of xor of all unordered triplets of the array
Given an array A, consisting of N non-negative integers, find the sum of xor of all unordered triplets of the array. For unordered triplets, the triplet (A[i], A[j], A[k]) is considered the same as triplets (A[j], A[i], A[k]) and all the other permutations. Since the answer can be large, calculate its mod to 10037. Examples: Input : A = [3, 5, 2, 1
11 min read
Find all triplets that sum to a given value or less
Given an array, arr[] and integer X. Find all the possible triplets from an arr[] whose sum is either equal to less than X. Example: Input : arr[] = {-1, 1, 3, 2}, X = 3Output: (-1, 1, 3), (-1, 1, 2)Explanation: If checked manually, the above two are the only triplets from possible 4 triplets whose sum is less than or equal to 3. Approach: This can
7 min read
Find bitwise XOR of all triplets formed from given three Arrays
Given three arrays arr1[], arr2[], and arr3[] consisting of non-negative integers. The task is to find the bitwise XOR of the XOR of all possible triplets that are formed by taking one element from each array. Examples: Input: arr1[] = {2, 3, 1}, arr2[] = {2, 4}, arr3[] = {3, 5}Output: 0Explanation: All possible triplets are (2, 2, 3), (2, 2, 5), (
11 min read
Find all triplets in a sorted array that forms Geometric Progression
Given a sorted array of distinct positive integers, print all triplets that forms Geometric Progression with integral common ratio.A geometric progression is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed, non-zero number called the common ratio. For example, the sequence 2, 6, 18, 54,... i
10 min read
Count all Grandparent-Parent-Child Triplets in a binary tree whose sum is greater than X
Given an integer X and a binary tree, the task is to count the number of triplet triplets of nodes such that their sum is greater than X and they have a grandparent -> parent -> child relationship. Example: Input: X = 100 10 / \ 1 22 / \ / \ 35 4 15 67 / \ / \ / \ / \ 57 38 9 10 110 312 131 414 / \ 8 39 Output: 6 The triplets are: 22 -> 15
15+ min read
Sum of Bitwise AND of all unordered triplets of an array
Given an array arr[] consisting of N positive integers, the task is to find the sum of Bitwise AND of all possible triplets (arr[i], arr[j], arr[k]) such that i < j < k. Examples: Input: arr[] = {3, 5, 4, 7}Output: 5Explanation: Sum of Bitwise AND of all possible triplets = (3 & 5 & 4) + (3 & 5 & 7) + (3 & 4 & 7) + (5
10 min read
Minimize sum of minimum and second minimum elements from all possible triplets
Given an array arr[], the task is to minimize the sum of minimum and second minimum elements from all possible triplets. One element can be a part of exactly one triplet. Input: arr[] = {1, 2, 4, 6, 7, 8, 3}, N = 7Output: 10Explanation: Here two triplets are formed as the size of arr[] is 7 and 7/3 = 2.Triplet 1 - {1, 6, 3} -> Two minimum elemen
5 min read
Print all triplets with given sum
Given an array of distinct elements. The task is to find triplets in array whose sum is equal to a given number. Examples: Input: arr[] = {0, -1, 2, -3, 1} sum = -2 Output: 0 -3 1 -1 2 -3 If we calculate the sum of the output, 0 + (-3) + 1 = -2 (-1) + 2 + (-3) = -2 Input: arr[] = {1, -2, 1, 0, 5} sum = 0 Output: 1 -2 1 If we calculate the sum of th
15+ min read
Print all triplets with sum S in given sorted Linked List
Given a sorted singly linked list as list of N distinct nodes (no two nodes have the same data) and an integer S. The task is to find all distinct triplets in the list that sum up to given integer S. Examples: Input: list = 1->2->4->5->6->8->9, S = 15Output: [(1, 5, 9), (1, 6, 8), (2, 4, 9), (2 ,5, 8), (4, 5, 6)]Explanation: These
15+ min read
All unique triplets that sum up to a given value
Given an array and a sum value, find all possible unique triplets in that array whose sum is equal to the given sum value. If no such triplets can be formed from the array, then print "No triplets can be formed", else print all the unique triplets. For example, if the given array is {12, 3, 6, 1, 6, 9} and the given sum is 24, then the unique tripl
15+ min read
Count all triplets whose sum is equal to a perfect cube
Given an array of n integers, count all different triplets whose sum is equal to the perfect cube i.e, for any i, j, k(i < j < k) satisfying the condition that a[i] + a[j] + a[j] = X3 where X is any integer. 3 ? n ? 1000, 1 ? a[i, j, k] ? 5000 Example: Input: N = 5 2 5 1 20 6 Output: 3 Explanation: There are only 3 triplets whose total sum is
10 min read
Find Maximum Sum of Mountain Triplets
Given an array A[] of integers. Then the task is to output the maximum sum of a triplet (Ai, Aj, Ak) such that it must follow the conditions: (i < j < k) and (Ai < Aj > Ak). If no such triplet exists, then output -1. Examples: Input: A[] = {1, 5, 4, 7, 3} Output: 15 Explanation: There are following 6 possible triplets following the cond
13 min read
Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k]
Given an array of positive integers of size n. Find the maximum sum of triplet( ai + aj + ak ) such that 0 <= i < j < k < n and ai < aj < ak. Input: a[] = 2 5 3 1 4 9Output: 16Explanation:All possible triplets are:-2 3 4 => sum = 92 5 9 => sum = 162 3 9 => sum = 143 4 9 => sum = 161 4 9 => sum = 14Maximum sum = 16Si
11 min read
Find all possible triangles with XOR of sides zero
Given an integer N, we need to find three integers(X, Y, Z) which can form a triangle with the following conditions: Lengths of sides are integers not exceeding N.XOR of three sides is 0, i.e., X ^ Y ^ Z = 0Area of triangle is greater than 0. Find all the possible triples which satisfy the above conditions. Examples: Input: 6 Output: 6 5 3 Input: 1
6 min read
Minimum steps to make sum and the product of all elements of array non-zero
Given an array arr of N integers, the task is to find the minimum steps in which the sum and product of all elements of the array can be made non-zero. In one step any element of the array can be incremented by 1.Examples: Input: N = 4, arr[] = {0, 1, 2, 3} Output: 1 Explanation: As product of all elements of the array is zero Increment the array e
7 min read
Rearrange array to make sum of all subarrays starting from first index non-zero
Given an array arr[] consisting of N integers, the task is to rearrange the array such that sum of all subarrays starting from the first index of the array is non-zero. If it is not possible to generate such arrangement, then print "-1". Examples: Input: arr[] = {-1, 1, -2, 3}Output: {-1, -2, 1, 3}Explanation: One of the possible rearrangement is {
12 min read
For all Array elements find Product of Sum of all smaller and Sum of all greater elements
Given an array arr[] of integers of length N, the task is to find the product of the sum of all the numbers larger than that number with the sum of all the numbers less than that number for each number in the array. Examples: Input: arr[] = {8, 4, 9, 3}, N = 4Output:- 63, 51, 0, 0Explanation:For first number 8: Sum of elements smaller than this is
15 min read
Print all triplets in sorted array that form AP
Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression) Examples : Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; Output : 6 9 12 2 12 22 12 17 22 2 17 32 12 22 32 9 22 35 2 22 42 22 32 42 Input : arr[] = { 3, 5, 6, 7, 8, 10, 12}; Output : 3 5 7 5 6 7 6 7 8 6 8 10 8 10 12 A simple so
12 min read
Maximum value of XOR among all triplets of an array
Given an array of integers 'arr', the task is to find the maximum XOR value of any triplet pair among all the possible triplet pairs. Note: An array element can be used more than once. Examples: Input: arr[] = {3, 4, 5, 6} Output: 7 The triplet with maximum XOR value is {4, 5, 6}. Input: arr[] = {1, 3, 8, 15} Output: 15 Approach: Store all possible
5 min read
Count triplets (a, b, c) such that a + b, b + c and a + c are all divisible by K
Given two integers 'N' and 'K', the task is to count the number of triplets (a, b, c) of positive integers not greater than 'N' such that 'a + b', 'b + c', and 'c + a' are all multiples of 'K'. Note that 'a', 'b' and 'c' may or may not be the same in a triplet. Examples: Input: N = 2, K = 2 Output: 2Explanation: All possible triplets are (1, 1, 1)
5 min read
Make all array elements equal by replacing triplets with their Bitwise XOR
Given an array arr[] of size N, the task is to find all the triplets (i, j, k) such that replacing the elements of the triplets with their Bitwise XOR values, i.e. replacing arr[i], arr[j], arr[k] with (arr[i] ^ arr[j] ^ arr[k]) makes all array elements equal. If more than one solution exists, print any of them. Otherwise, print -1. Examples: Input
10 min read
Count triplets (a, b, c) such that a + b, b + c and a + c are all divisible by K | Set 2
Given two positive integers N and K, the task is to count the number of triplets (a, b, c) such that 0 < a, b, c < N and (a + b), (b + c) and (c + a) are all multiples of K. Examples: Input: N = 2, K = 2Output: 2Explanation: All possible triplets that satisfy the given property are (1, 1, 1) and (2, 2, 2).Therefore, the total count is 2. Inpu
6 min read
Count of all triplets such that XOR of two equals to third element
Given an array arr[] of positive integers, the task is to find the count of all triplets such that XOR of two equals the third element. In other words count all the triplets (i, j, k) such that arr[i] ^ arr[j] = arr[k] and i < j < k. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1Explanation: One such triplet exists in this i.e {1, 2, 3} where
6 min read
Count all triplets from given Array whose bitwise XOR is equal to K
Given an array arr[] which contains N positive integers and an integer K. The task is to count all triplets whose XOR is equal to the K. i.e arr[ i ] ^ arr[ j ] ^ arr[ k ] = X where 0 ≤ i < j < k < N ( 0 based indexing) Examples: Input: arr[] = { 2, 1, 3, 7, 5, 4}, K = 5Output: 2Explanation: In the above array there are two triplets whose
15+ min read
Javascript Program for Print all triplets in sorted array that form AP
Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression) Examples : Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 };Output :6 9 122 12 2212 17 222 17 3212 22 329 22 352 22 4222 32 42Input : arr[] = { 3, 5, 6, 7, 8, 10, 12};Output :3 5 75 6 76 7 86 8 108 10 12A simple solution is to run
4 min read
Find N distinct integers with zero sum
Given an integer N, our task is to print N distinct numbers such that their sum is 0.Examples: Input: N = 3 Output: 1, -1, 0 Explanation: On adding the numbers that is 1 + (-1) + 0 the sum is 0.Input: N = 4 Output: 1, -1, 2, -2 Explanation: On adding the numbers that is 1 + (-1) + 2 + (-2) the sum is 0. Approach: To solve the problem mentioned abov
4 min read