VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-gp-geometric-progression-subsequences-size-3/

⇱ Number of GP (Geometric Progression) subsequences of size 3 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of GP (Geometric Progression) subsequences of size 3

Last Updated : 24 Mar, 2023

Given n elements and a ratio r, find the number of G.P. subsequences with length 3. A subsequence is considered GP with length 3 with ration r.

Examples:

Input : arr[] = {1, 1, 2, 2, 4}
 r = 2
Output : 4 
Explanation: Any of the two 1s can be chosen 
as the first element, the second element can 
be any of the two 2s, and the third element 
of the subsequence must be equal to 4.
 
Input : arr[] = {1, 1, 2, 2, 4}
 r = 3
Output : 0

A naive approach is to use three nested for loops and check for every subsequence with length 3 and keep a count of the subsequences. The complexity is O(n3).

An efficient approach is to solve the problem for the fixed middle element of progression. This means that if we fix element a[i] as middle, then it must be multiple of r, and a[i]/r and a[i]*r must be present. We count the number of occurrences of a[i]/r and a[i]*r and then multiply the counts. To do this, we can use the concept of hashing where we store the count of all possible elements in two hash maps, one indicating the number of elements on the left and the other indicating the number of elements to the right.

Below is the implementation of the above approach


Output: 
6

Time Complexity: O(n), where n represents the size of the given array.

Auxiliary Space: O(n), where n represents the size of the given array.

The above solution does not handle the case when r is 1 : For example, for input = {1,1,1,1,1}, there are 10 possible for G.P. subsequences of length 3, which can be calculated by using 5C3. Such a procedure should be implemented for all cases where r = 1. Below is the modified code to handle this.


Output: 
6

Time Complexity: O(n), where n represents the size of the given array.

Auxiliary Space: O(n), where n represents the size of the given array.

Comment