Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Pairs from an array that satisfy the given condition
Next article icon

Count of triplets in an array that satisfy the given conditions

Last Updated : 14 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of N elements, the task is to find the count of triplets (arr[i], arr[j], arr[k]) such that (arr[i] + arr[j] + arr[k] = L) and (L % arr[i] = L % arr[j] = L % arr[k] = 0.
Examples: 
 

Input: arr[] = {2, 4, 5, 6, 7} 
Output: 1 
Only possible triplet is {2, 4, 6}
Input: arr[] = {4, 4, 4, 4, 4} 
Output: 10 
 

 

Approach: 
 

  • Consider the equations below: 
     

L = a * arr[i], L = b * arr[j] and L = c * arr[k]. 
Thus, arr[i] = L / a, arr[j] = L / b and arr[k] = L / c. 
So, using this in arr[i] + arr[j] + arr[k] = L gives L / a + L / b + L / c = L 
or 1 / a + 1 / b + 1 / c = 1. 
Now, there can only be 10 possible solutions of the above equation, which are 
{2, 3, 6} 
{2, 4, 4} 
{2, 6, 3} 
{3, 2, 6} 
{3, 3, 3} 
{3, 6, 2} 
{4, 2, 4} 
{4, 4, 2} 
{6, 2, 3} 
{6, 3, 2}
All possible triplets (arr[i], arr[j], arr[k]) will satisfy these solutions. So, all these solutions can be stored in a 2D array say test[][3]. So, that all the triplets which satisfy these solutions can be found. 
 

  •  
  • For all i from 1 to N. Consider arr[i] as the middle element of the triplet. And find corresponding first and third elements of the triplet for all possible solutions of the equation 1 / a + 1 / b + 1 / c = 1. Find the answer for all the cases and add them to the final answer.
  • Maintain the indices where arr[i] occurs in the array. For a given possible solution of equation X and for every number arr[i] keep the number as middle element of triplet and find the first and the third element. Apply binary search on the available set of indices for the first and the third element to find the number of occurrence of the first element from 1 to i – 1 and the number of occurrences of the third element from i + 1 to N. Multiply both the values and add it to the final answer.

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX 100001
#define ROW 10
#define COl 3
 
vector<int> indices[MAX];
 
// All possible solutions of the
// equation 1/a + 1/b + 1/c = 1
int test[ROW][COl] = { { 2, 3, 6 },
                       { 2, 4, 4 },
                       { 2, 6, 3 },
                       { 3, 2, 6 },
                       { 3, 3, 3 },
                       { 3, 6, 2 },
                       { 4, 2, 4 },
                       { 4, 4, 2 },
                       { 6, 2, 3 },
                       { 6, 3, 2 } };
 
// Function to find the triplets
int find_triplet(int array[], int n)
{
    int answer = 0;
 
    // Storing indices of the elements
    for (int i = 0; i < n; i++) {
        indices[array[i]].push_back(i);
    }
 
    for (int i = 0; i < n; i++) {
        int y = array[i];
 
        for (int j = 0; j < ROW; j++) {
            int s = test[j][1] * y;
 
            // Check if y can act as the middle
            // element of triplet with the given
            // solution of 1/a + 1/b + 1/c = 1
            if (s % test[j][0] != 0)
                continue;
            if (s % test[j][2] != 0)
                continue;
 
            int x = s / test[j][0];
            ll z = s / test[j][2];
            if (x > MAX || z > MAX)
                continue;
 
            int l = 0;
            int r = indices[x].size() - 1;
 
            int first = -1;
 
            // Binary search to find the number of
            // possible values of the first element
            while (l <= r) {
                int m = (l + r) / 2;
 
                if (indices[x][m] < i) {
                    first = m;
                    l = m + 1;
                }
                else {
                    r = m - 1;
                }
            }
 
            l = 0;
            r = indices[z].size() - 1;
 
            int third = -1;
 
            // Binary search to find the number of
            // possible values of the third element
            while (l <= r) {
                int m = (l + r) / 2;
 
                if (indices[z][m] > i) {
                    third = m;
                    r = m - 1;
                }
                else {
                    l = m + 1;
                }
            }
 
            if (first != -1 && third != -1) {
 
                // Contribution to the answer would
                // be the multiplication of the possible
                // values for the first and the third element
                answer += (first + 1) * (indices[z].size() - third);
            }
        }
    }
 
    return answer;
}
 
// Driver code
int main()
{
    int array[] = { 2, 4, 5, 6, 7 };
    int n = sizeof(array) / sizeof(array[0]);
 
    cout << find_triplet(array, n);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
static int MAX = 100001;
static int ROW = 10;
static int COl = 3;
 
static Vector<Integer> []indices = new Vector[MAX];
 
// All possible solutions of the
// equation 1/a + 1/b + 1/c = 1
static int test[][] = { { 2, 3, 6 }, { 2, 4, 4 },
                        { 2, 6, 3 }, { 3, 2, 6 },
                        { 3, 3, 3 }, { 3, 6, 2 },
                        { 4, 2, 4 }, { 4, 4, 2 },
                        { 6, 2, 3 }, { 6, 3, 2 } };
 
// Function to find the triplets
static int find_triplet(int array[], int n)
{
    int answer = 0;
    for (int i = 0; i < MAX; i++)
    {
        indices[i] = new Vector<>();
    }
     
    // Storing indices of the elements
    for (int i = 0; i < n; i++)
    {
        indices[array[i]].add(i);
    }
 
    for (int i = 0; i < n; i++)
    {
        int y = array[i];
 
        for (int j = 0; j < ROW; j++)
        {
            int s = test[j][1] * y;
 
            // Check if y can act as the middle
            // element of triplet with the given
            // solution of 1/a + 1/b + 1/c = 1
            if (s % test[j][0] != 0)
                continue;
            if (s % test[j][2] != 0)
                continue;
 
            int x = s / test[j][0];
            int z = s / test[j][2];
            if (x > MAX || z > MAX)
                continue;
 
            int l = 0;
            int r = indices[x].size() - 1;
 
            int first = -1;
 
            // Binary search to find the number of
            // possible values of the first element
            while (l <= r)
            {
                int m = (l + r) / 2;
 
                if (indices[x].get(m) < i)
                {
                    first = m;
                    l = m + 1;
                }
                else
                {
                    r = m - 1;
                }
            }
 
            l = 0;
            r = indices[z].size() - 1;
 
            int third = -1;
 
            // Binary search to find the number of
            // possible values of the third element
            while (l <= r)
            {
                int m = (l + r) / 2;
 
                if (indices[z].get(m) > i)
                {
                    third = m;
                    r = m - 1;
                }
                else
                {
                    l = m + 1;
                }
            }
 
            if (first != -1 && third != -1)
            {
 
                // Contribution to the answer would
                // be the multiplication of the possible
                // values for the first and the third element
                answer += (first + 1) * (indices[z].size() - third);
            }
        }
    }
    return answer;
}
 
// Driver code
public static void main(String []args)
{
    int array[] = { 2, 4, 5, 6, 7 };
    int n = array.length;
 
    System.out.println(find_triplet(array, n));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 implementation of the approach
MAX = 100001
ROW = 10
COL = 3
 
indices = [0] * MAX
 
# All possible solutions of the
# equation 1/a + 1/b + 1/c = 1
test = [[2, 3, 6], [2, 4, 4],
        [2, 6, 3], [3, 2, 6],
        [3, 3, 3], [3, 6, 2],
        [4, 2, 4], [4, 4, 2],
        [6, 2, 3], [6, 3, 2]]
 
# Function to find the triplets
def find_triplet(array, n):
    answer = 0
 
    for i in range(MAX):
        indices[i] = []
 
    # Storing indices of the elements
    for i in range(n):
        indices[array[i]].append(i)
 
    for i in range(n):
        y = array[i]
 
        for j in range(ROW):
            s = test[j][1] * y
 
            # Check if y can act as the middle
            # element of triplet with the given
            # solution of 1/a + 1/b + 1/c = 1
            if s % test[j][0] != 0:
                continue
            if s % test[j][2] != 0:
                continue
 
            x = s // test[j][0]
            z = s // test[j][2]
            if x > MAX or z > MAX:
                continue
 
            l = 0
            r = len(indices[x]) - 1
            first = -1
 
            # Binary search to find the number of
            # possible values of the first element
            while l <= r:
                m = (l + r) // 2
 
                if indices[x][m] < i:
                    first = m
                    l = m + 1
                else:
                    r = m - 1
 
            l = 0
            r = len(indices[z]) - 1
            third = -1
 
            # Binary search to find the number of
            # possible values of the third element
            while l <= r:
                m = (l + r) // 2
 
                if indices[z][m] > i:
                    third = m
                    r = m - 1
                else:
                    l = m + 1
 
            if first != -1 and third != -1:
 
                # Contribution to the answer would
                # be the multiplication of the possible
                # values for the first and the third element
                answer += (first + 1) * (len(indices[z]) - third)
    return answer
 
# Driver Code
if __name__ == "__main__":
    array = [2, 4, 5, 6, 7]
    n = len(array)
 
    print(find_triplet(array, n))
 
# This code is contributed by
# sanjeev2552
 
 

C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
static int MAX = 100001;
static int ROW = 10;
static int COl = 3;
 
static List<int> []indices = new List<int>[MAX];
 
// All possible solutions of the
// equation 1/a + 1/b + 1/c = 1
static int [,]test = { { 2, 3, 6 }, { 2, 4, 4 },
                       { 2, 6, 3 }, { 3, 2, 6 },
                       { 3, 3, 3 }, { 3, 6, 2 },
                       { 4, 2, 4 }, { 4, 4, 2 },
                       { 6, 2, 3 }, { 6, 3, 2 } };
 
// Function to find the triplets
static int find_triplet(int []array, int n)
{
    int answer = 0;
    for (int i = 0; i < MAX; i++)
    {
        indices[i] = new List<int>();
    }
     
    // Storing indices of the elements
    for (int i = 0; i < n; i++)
    {
        indices[array[i]].Add(i);
    }
 
    for (int i = 0; i < n; i++)
    {
        int y = array[i];
 
        for (int j = 0; j < ROW; j++)
        {
            int s = test[j, 1] * y;
 
            // Check if y can act as the middle
            // element of triplet with the given
            // solution of 1/a + 1/b + 1/c = 1
            if (s % test[j, 0] != 0)
                continue;
            if (s % test[j, 2] != 0)
                continue;
 
            int x = s / test[j, 0];
            int z = s / test[j, 2];
            if (x > MAX || z > MAX)
                continue;
 
            int l = 0;
            int r = indices[x].Count - 1;
 
            int first = -1;
 
            // Binary search to find the number of
            // possible values of the first element
            while (l <= r)
            {
                int m = (l + r) / 2;
 
                if (indices[x][m] < i)
                {
                    first = m;
                    l = m + 1;
                }
                else
                {
                    r = m - 1;
                }
            }
 
            l = 0;
            r = indices[z].Count - 1;
 
            int third = -1;
 
            // Binary search to find the number of
            // possible values of the third element
            while (l <= r)
            {
                int m = (l + r) / 2;
 
                if (indices[z][m] > i)
                {
                    third = m;
                    r = m - 1;
                }
                else
                {
                    l = m + 1;
                }
            }
 
            if (first != -1 && third != -1)
            {
 
                // Contribution to the answer would
                // be the multiplication of the possible
                // values for the first and the third element
                answer += (first + 1) * (indices[z].Count - third);
            }
        }
    }
    return answer;
}
 
// Driver code
public static void Main(String []args)
{
    int []array = { 2, 4, 5, 6, 7 };
    int n = array.Length;
 
    Console.WriteLine(find_triplet(array, n));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// Javascript implementation of the approach
 
var MAX = 100001
var ROW = 10
var COl = 3
 
var indices = Array.from(Array(MAX), ()=>new Array());
 
// All possible solutions of the
// equation 1/a + 1/b + 1/c = 1
var test = [ [ 2, 3, 6 ],
                       [ 2, 4, 4 ],
                       [ 2, 6, 3 ],
                       [ 3, 2, 6 ],
                       [ 3, 3, 3 ],
                       [ 3, 6, 2 ],
                       [ 4, 2, 4 ],
                       [ 4, 4, 2 ],
                       [ 6, 2, 3 ],
                       [ 6, 3, 2 ] ];
 
// Function to find the triplets
function find_triplet(array, n)
{
    var answer = 0;
 
    // Storing indices of the elements
    for (var i = 0; i < n; i++) {
        indices[array[i]].push(i);
    }
 
    for (var i = 0; i < n; i++) {
        var y = array[i];
 
        for (var j = 0; j < ROW; j++) {
            var s = test[j][1] * y;
 
            // Check if y can act as the middle
            // element of triplet with the given
            // solution of 1/a + 1/b + 1/c = 1
            if (s % test[j][0] != 0)
                continue;
            if (s % test[j][2] != 0)
                continue;
 
            var x = s / test[j][0];
            var z = s / test[j][2];
            if (x > MAX || z > MAX)
                continue;
 
            var l = 0;
            var r = indices[x].length - 1;
 
            var first = -1;
 
            // Binary search to find the number of
            // possible values of the first element
            while (l <= r) {
                var m = (l + r) / 2;
 
                if (indices[x][m] < i) {
                    first = m;
                    l = m + 1;
                }
                else {
                    r = m - 1;
                }
            }
 
            l = 0;
            r = indices[z].length - 1;
 
            var third = -1;
 
            // Binary search to find the number of
            // possible values of the third element
            while (l <= r) {
                var m = (l + r) / 2;
 
                if (indices[z][m] > i) {
                    third = m;
                    r = m - 1;
                }
                else {
                    l = m + 1;
                }
            }
 
            if (first != -1 && third != -1) {
 
                // Contribution to the answer would
                // be the multiplication of the possible
                // values for the first and the third element
                answer += (first + 1) * (indices[z].length - third);
            }
        }
    }
 
    return answer;
}
 
// Driver code
var array = [2, 4, 5, 6, 7];
var n = array.length;
document.write( find_triplet(array, n));
 
</script>
 
 
Output: 
1

 



Next Article
Pairs from an array that satisfy the given condition

K

krikti
Improve
Article Tags :
  • Arrays
  • DSA
  • Pattern Searching
  • Searching
Practice Tags :
  • Arrays
  • Pattern Searching
  • Searching

Similar Reads

  • Pairs from an array that satisfy the given condition
    Given an array arr[], the task is to count all the valid pairs from the array. A pair (arr[i], arr[j]) is said to be valid if func( arr[i] ) + func( arr[j] ) = func( XOR(arr[i], arr[j]) ) where func(x) returns the number of set bits in x. Examples: Input: arr[] = {2, 3, 4, 5, 6} Output: 3 (2, 4), (2
    9 min read
  • Count triplet pairs (A, B, C) of points in 2-D space that satisfy the given condition
    Given N points in 2 dimensional space. The task is to count the number of triplets pairs (A, B, C) such that point B is the midpoint of line segment formed by joining points A and C.Examples: Input: points = {{1, 1}, {2, 2}, {3, 3}} Output: 1 The point (2, 2) is the midpoint of the line segment join
    6 min read
  • Count valid pairs in the array satisfying given conditions
    Given an array of integers arr[], the task is to count the number of valid pairs of elements from arr. A pair (arr[x], arr[y]) is said to be invalid if arr[x] < arr[y]abs(arr[x] - arr[y]) is odd Note: Pairs (arr[x], arr[y]) and (arr[y], arr[x]) are two different pairs when x != y and the value of
    5 min read
  • Count of triplets that satisfy the given equation
    Given an array arr[] of N non-negative integers. The task is to count the number of triplets (i, j, k) where 0 ? i < j ? k < N such that A[i] ^ A[i + 1] ^ ... ^ A[j - 1] = A[j] ^ A[j + 1] ^ ... ^ A[k] where ^ is the bitwise XOR.Examples: Input: arr[] = {2, 5, 6, 4, 2} Output: 2 The valid tripl
    5 min read
  • Count number of coordinates from an array satisfying the given conditions
    Given an array arr[] consisting of N coordinates in the Cartesian Plane, the task is to find the number of coordinates, such as (X, Y), that satisfies all the following conditions: All possible arr[i][0] must be less than X and arr[i][1] must be equal to Y.All possible arr[i][0] must be greater than
    10 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 of triplets (a, b, c) in the Array such that a divides b and b divides c
    Given an array arr[] of positive integers of size N, the task is to count number of triplets in the array such that a[i] divides a[j] and a[j] divides a[k] and i < j < k.Examples: Input: arr[] = {1, 2, 3, 4, 5, 6} Output: 3 Explanation: The triplets are: (1, 2, 4), (1, 2, 6), (1, 3, 6).Input:
    8 min read
  • Count of distinct alternate triplets of indices from given Array | Set 2
    Given a binary array arr[] of size N, the task is to find the count of distinct alternating triplets. Note: A triplet is alternating if the values of those indices are in {0, 1, 0} or {1, 0, 1} form. Examples: Input: arr[] = {0, 0, 1, 1, 0, 1} Output: 6Explanation: Here four sequence of "010" and tw
    9 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
  • Count of triplets in a given Array having GCD K
    Given an integer array arr[] and an integer K, the task is to count all triplets whose GCD is equal to K.Examples: Input: arr[] = {1, 4, 8, 14, 20}, K = 2 Output: 3 Explanation: Triplets (4, 14, 20), (8, 14, 20) and (4, 8, 14) have GCD equal to 2.Input: arr[] = {1, 2, 3, 4, 5}, K = 7 Output: 0 Appro
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences