Count Triplets such that one of the numbers can be written as sum of the other two in C++



In this article, We are given an array arr[] of integers with length n. Our task is to count the number of triplets such that the sum of any two numbers is equal to the third number.

Example

Here is an example of counting the triplets whose sum of any two numbers equals the third one:

Input:
arr[]= {1, 2, 2, 3, 4}

Output:
4

The explanation of the above example is as follows:

Triplet 1: (1,2,3) => 1+2=3
Triplet 2: (1,2,3) => 1+2=3
Triplet 3: (1,3,4) => 1+3=4
Triplet 4: (2,2,4) => 2+2=4

Here are the approaches that we will be using in this article to count the triplets:

Using Brute Force Approach

The following approach uses the brute force method where we have used three for loops. The outer loop selects the first element, the second loop selects the second array element and the third loop selects the third element. We check if the sum of the first two array elements is equal to the third element or not. We increase the count value if any of the elements is the sum of the other two elements and the count is returned.

Example

The following example counts the number of triplets when one number is the sum of the other two in the triplet using the brute force technique.

#include <iostream>
using namespace std;

int countTriplets(int arr[], int n)
{
   int count = 0;
   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 (arr[i] + arr[j] == arr[k] || arr[j] + arr[k] == arr[i] || arr[k] + arr[i] == arr[j])
            {
               count++;
            }
         }
      }
   }
   return count;
}
int main()
{
   int arr[] = {1, 2, 2, 3, 4};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Given array: ";
   for (int i = 0; i < n; i++)
   {
      cout << arr[i] << " ";
   }
   cout << endl
        << "Number of triplets : " << countTriplets(arr, n);
   return 0;
}

The output of the above code is as follows:

Given array: 1 2 2 3 4 
Number of triplets : 4

Using Two Pointers

In this approach, we have used the two pointer technique. We keep one element as a fixed element and use both pointers to traverse the array to find elements whose sum equals the the fixed element.

  • First, we sort the given array in the ascending order.
  • Then using a for loop we fix the last element in every iteration and search the array for elements using the two pointers (left and right) whose sum equals the fixed element.
  • If the sum of the left and right array elements is less than the third element then we increase the left pointer and decrease the right pointer if we get a sum value greater than the third element.
  • If the sum of two elements equals the third element is found, we check for duplicates.
  • If the left and right have the same value i.e., for example {2, 2, 4}. In this case, we use the formula (n * (n-1))/2 to get the unique pair and update the count value by adding the pair value to the count.
  • If the left and right values are different such as {2, 2, 4, 4, 6} then we update the leftCount and rightCount.
  • We update the count by adding the product of left and right counts. At the end, the final count is returned.

Example

The following example uses the above steps to count the triplets using the two pointers technique:

#include <iostream>
#include <algorithm>
using namespace std;
int countTriplets(int arr[], int n)
{
   sort(arr, arr + n);
   int count = 0;
   // Find other two elements while fixing the third one
   for (int i = n - 1; i >= 2; i--)
   {
      int left = 0, right = i - 1;
      while (left < right)
      {
         int sum = arr[left] + arr[right];
         if (sum == arr[i])
         {
            if (arr[left] == arr[right])
            {
               // For counting duplicates pairs 
               int pairs = (right - left + 1) * (right - left) / 2;
               count += pairs;
               break;
            }
            else
            {
               // Count duplicates on left side
               int leftCount = 1;
               while (left + 1 < right && arr[left] == arr[left + 1])
               {
                  leftCount++;
                  left++;
               }
               // Counting duplicates on right side
               int rightCount = 1;
               while (right - 1 > left && arr[right] == arr[right - 1])
               {
                  rightCount++;
                  right--;
               }
               
               count += leftCount * rightCount;
               left++;
               right--;
            }
         }
         else if (sum < arr[i])
         {
            left++;
         }
         else
         {
            right--;
         }
      }
   }
   return count;
}
int main()
{
   int arr[] = {2, 2, 4, 6, 10};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Given array: ";
   for (int i = 0; i < n; i++)
   {
      cout << arr[i] << " ";
   }
   cout << endl
        << "Number of triplets : " << countTriplets(arr, n);
   return 0;
}

The output of the above code is as follows:

Given array: 2 2 4 6 10 
Number of triplets : 4

Using Frequency Map

In this approach, we have used an unordered map to store the frequency of array elements. An unordered map is a dictionary-like data structure where a single value is associated with each unique key. It enables fast retrieval of individual elements based on their keys.

  • Using the unordered map, we get the frequency of each array element.
  • Then, using a nested for loop we get pairs of elements and calculate their sum.
  • Then we search the sum value in the freq unordered map using find() function.
  • We increase the count by 1 if the sum is found in the freq.
  • We repeat the above three steps until we calculate the sum of each pair then the count is returned.

Example

Here is an example implementing the above steps to count the triplets using an unordered map:

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

int countTriplets(int arr[], int n)
{
   unordered_map<int, int> freq;
   int count = 0;

   for (int i = 0; i < n; i++)
   {
      freq[arr[i]]++;
   }

   for (int i = 0; i < n; i++)
   {
      for (int j = i + 1; j < n; j++)
      {
         int sum = arr[i] + arr[j];
         if (freq.find(sum) != freq.end())
         {
            count++;
         }
      }
   }

   return count;
}

int main()
{
   int arr[] = {2, 2, 4, 6, 10};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Given array: ";
   for (int i = 0; i < n; i++)
   {
      cout << arr[i] << " ";
   }
   cout << endl
        << "Number of triplets : " << countTriplets(arr, n);
   return 0;
}

The output of the above code is as follows:

Given array: 2 2 4 6 10 
Number of triplets : 4

Complexity Comparison

Here is a comparison of the time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Brute Force O(n^3) O(1)
Two Pointers O(n^2) O(1)
Frequency Map O(n^2) O(n)
Updated on: 2025-07-01T15:32:12+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements