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.
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 |
3
Time Complexity: O(N2)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Count triplets in an array such that i<j<k and a[j] - a[i] = a[k] - a[j] = D
- Count of triplets (a, b, c) in the Array such that a divides b and b divides c
- Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
- Rearrange array to maximize count of triplets (i, j, k) such that arr[i] > arr[j] < arr[k] and i < j < k
- Count of triplets from the given Array such that sum of any two elements is the third element
- Count number of triplets (a, b, c) such that a^2 + b^2 = c^2 and 1 <= a <= b <= c <= n
- Count Triplets such that one of the numbers can be written as sum of the other two
- Count the triplets such that A[i] < B[j] < C[k]
- Count triplets such that sum of any two number is equal to third | Set 2
- Count of triplets of numbers 1 to N such that middle element is always largest
- Find number of triplets in array such that a[i]>a[j]>a[k] and i<j<k
- Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k]
- Number of triplets such that each value is less than N and each pair sum is a multiple of K
- Maximize sum of array by reducing array elements to contain no triplets (i, j, k) where a[i] < a[j] and a[i] < a[k] and j <i < k
- Maximum number of unique Triplets such that each element is selected only once
- Count of triplets in an array that satisfy the given conditions
- Count of triplets in a given Array having GCD K
- Count triplets having product 0 from a given array
- Count the number of unordered triplets with elements in increasing order and product less than or equal to integer X
- Count triplets with sum smaller than a given value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

