Count of triplets in an Array such that A[i] * A[j] = A[k] and i < j < k

Given an array A[ ] consisting of N positive integers, the task is to find the number of triplets A[i], A[j] & A[k] in the array such that i < j < k and A[i] * A[j] = A[k].
Examples:
Input: N = 5, A[ ] = {2, 3, 4, 6, 12}Â
Output: 3Â
Explanation:Â
The valid triplets from the given array are:Â
(A[0], A[1], A[3]) = (2, 3, 6) where (2*3 = 6)Â
(A[0], A[3], A[4]) = (2, 6, 12) where (2*6 = 12)Â
(A[1], A[2], A[4]) = (3, 4, 12) where (3*4 = 12)Â
Hence, a total of 3 triplets exists which satisfies the given condition.Input: N = 3, A[ ] = {1, 1, 1}Â
Output: 1Â
Explanation:Â
The only valid triplet is (A[0], A[1], A[2]) = (1, 1, 1)Â
Naive Approach:Â
The simplest approach to solve the problem is to generate all possible triplets and for each triplet, check if it satisfies the required condition. If found to be true, increase the count of triplets. After complete traversal of the array and generating all possible triplets, print the final count.Â
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;Â
// Returns total number of// valid triplets possibleint countTriplets(int A[], int N){    // Stores the count    int ans = 0;Â
    for (int i = 0; i < N; i++) {        for (int j = i + 1; j < N; j++) {            for (int k = j + 1; k < N; k++) {                if (A[i] * A[j] == A[k])                    ans++;            }        }    }Â
    // Return the final count    return ans;}Â
// Driver Codeint main(){Â Â Â Â int N = 5;Â Â Â Â int A[] = { 2, 3, 4, 6, 12 };Â
    cout << countTriplets(A, N);Â
    return 0;} |
Java
/*package whatever //do not write package name here */import java.io.*;Â
public class GFG {Â
  // Returns total number of  // valid triplets possible  static int countTriplets(int A[], int N)  {    // Stores the count    int ans = 0;Â
    for (int i = 0; i < N; i++) {      for (int j = i + 1; j < N; j++) {        for (int k = j + 1; k < N; k++) {          if (A[i] * A[j] == A[k])            ans++;        }      }    }Â
    // Return the final count    return ans;  }Â
  public static void main (String[] args) {Â
    int N = 5;    int A[] = { 2, 3, 4, 6, 12 };Â
    System.out.println(countTriplets(A, N));  }}Â
// This code is contributed by aadityaburujwale. |
Python3
# Python3 Program to implement# the above approachÂ
# Returns total number of# valid triplets possibledef countTriplets( A, N):       # Stores the count    ans = 0;Â
    for i in range(0, N):        for j in range(i + 1, N):            for k in range(j + 1, N):                if (A[i] * A[j] == A[k]):                    ans += 1;             # Return the final count    return ans;Â
# Driver CodeN = 5;A = [ 2, 3, 4, 6, 12 ];print(countTriplets(A, N));Â
# This code is contributed by poojaagrawal2. |
C#
// Include namespace systemusing System;Â
Â
public class GFG{    // Returns total number of    // valid triplets possible    public static int countTriplets(int[] A, int N)    {        // Stores the count        var ans = 0;        for (int i = 0; i < N; i++)        {            for (int j = i + 1; j < N; j++)            {                for (int k = j + 1; k < N; k++)                {                    if (A[i] * A[j] == A[k])                    {                        ans++;                    }                }            }        }        // Return the final count        return ans;    }    public static void Main(String[] args)    {        var N = 5;        int[] A = {2, 3, 4, 6, 12};        Console.WriteLine(countTriplets(A, N));    }} |
Javascript
// Javascript Program to implement// the above approachÂ
// Returns total number of// valid triplets possiblefunction countTriplets(A, N){    // Stores the count    let ans = 0;Â
    for (let i = 0; i < N; i++) {        for (let j = i + 1; j < N; j++) {            for (let k = j + 1; k < N; k++) {                if (A[i] * A[j] == A[k])                    ans++;            }        }    }Â
    // Return the final count    return ans;}Â
// Driver Codelet N = 5;let A = [ 2, 3, 4, 6, 12 ];Â
console.log(countTriplets(A, N)); |
3
Time Complexity: O(N3)Â
Auxiliary Space: O(1)
Efficient Approach:Â
The above approach can be optimized using Two Pointers and HashMap.Â
Follow the steps below to solve the problem:Â
- Initialize a Map to store frequencies of array elements.
- Iterate over the array in reverse, i.e. loop with a variable j in the range [N – 2, 1].
- For every j, increase the count of A[j + 1] in the map. Iterate over the range [0, j – 1] using variable i and check if A[i] * A[j] is present in the map or not.
- If A[i] * A[j] is found in the map, increase the count of triplets by the frequency of A[i] * A[j] stored in the map.
- After complete traversal of the array, print the final count.
Below is the implementation of the above approach:
C++
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;Â
// Returns total number of// valid triplets possibleint countTriplets(int A[], int N){    // Stores the count    int ans = 0;Â
    // Map to store frequency    // of array elements    map<int, int> map;Â
    for (int j = N - 2; j >= 1; j--) {Â
        // Increment the frequency        // of A[j+1] as it can be        // a valid A[k]        map[A[j + 1]]++;Â
        for (int i = 0; i < j; i++) {Â
            int target = A[i] * A[j];Â
            // If target exists in the map            if (map.find(target)                != map.end())                ans += map[target];        }    }Â
    // Return the final count    return ans;}Â
// Driver Codeint main(){Â Â Â Â int N = 5;Â Â Â Â int A[] = { 2, 3, 4, 6, 12 };Â
    cout << countTriplets(A, N);Â
    return 0;} |
Java
// Java program to implement// the above approachimport java.util.*;Â
class GFG{Â
// Returns total number of// valid triplets possiblestatic int countTriplets(int A[], int N){         // Stores the count    int ans = 0;Â
    // Map to store frequency    // of array elements    HashMap<Integer,            Integer> map = new HashMap<Integer,                                       Integer>();                                            for(int j = N - 2; j >= 1; j--)     {Â
        // Increment the frequency        // of A[j+1] as it can be        // a valid A[k]        if(map.containsKey(A[j + 1]))            map.put(A[j + 1], map.get(A[j + 1]) + 1);        else            map.put(A[j + 1], 1);Â
        for(int i = 0; i < j; i++)         {            int target = A[i] * A[j];Â
            // If target exists in the map            if (map.containsKey(target))                ans += map.get(target);        }    }Â
    // Return the final count    return ans;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int N = 5;Â Â Â Â int A[] = { 2, 3, 4, 6, 12 };Â
    System.out.print(countTriplets(A, N));}}Â
// This code is contributed by sapnasingh4991 |
Python3
# Python3 program for the above approachfrom collections import defaultdictÂ
# Returns total number of# valid triplets possibledef countTriplets(A, N):Â
    # Stores the count    ans = 0Â
    # Map to store frequency    # of array elements    map = defaultdict(lambda: 0)Â
    for j in range(N - 2, 0, -1):Â
        # Increment the frequency        # of A[j+1] as it can be        # a valid A[k]        map[A[j + 1]] += 1Â
        for i in range(j):            target = A[i] * A[j]Â
            # If target exists in the map            if(target in map.keys()):                ans += map[target]Â
    # Return the final count     return ansÂ
# Driver codeif __name__ == '__main__':Â
    N = 5    A = [ 2, 3, 4, 6, 12 ]Â
    print(countTriplets(A, N))Â
# This code is contributed by Shivam Singh |
C#
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{Â
// Returns total number of// valid triplets possiblestatic int countTriplets(int []A, int N){         // Stores the count    int ans = 0;Â
    // Map to store frequency    // of array elements    Dictionary<int,               int> map = new Dictionary<int,                                         int>();                                            for(int j = N - 2; j >= 1; j--)     {Â
        // Increment the frequency        // of A[j+1] as it can be        // a valid A[k]        if(map.ContainsKey(A[j + 1]))            map[A[j + 1]] = map[A[j + 1]] + 1;        else            map.Add(A[j + 1], 1);Â
        for(int i = 0; i < j; i++)         {            int target = A[i] * A[j];Â
            // If target exists in the map            if (map.ContainsKey(target))                ans += map[target];        }    }Â
    // Return the readonly count    return ans;}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int N = 5;Â Â Â Â int []A = { 2, 3, 4, 6, 12 };Â
    Console.Write(countTriplets(A, N));}}Â
// This code is contributed by sapnasingh4991 |
Javascript
<script>Â
// Javascript program to implement// the above approach  // Returns total number of// valid triplets possiblefunction countTriplets(A, N){          // Stores the count    let ans = 0;      // Map to store frequency    // of array elements    let map = new Map();                                             for(let j = N - 2; j >= 1; j--)    {          // Increment the frequency        // of A[j+1] as it can be        // a valid A[k]        if(map.has(A[j + 1]))            map.set(A[j + 1], map.get(A[j + 1]) + 1);        else            map.set(A[j + 1], 1);          for(let i = 0; i < j; i++)        {            let target = A[i] * A[j];              // If target exists in the map            if (map.has(target))                ans += map.get(target);        }    }      // Return the final count    return ans;}  // Driver code    let N = 5;    let A = [ 2, 3, 4, 6, 12 ];      document.write(countTriplets(A, N));Â
// This code is contributed by souravghosh0416.</script> |
3
Time Complexity: O(N2)Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



