Given a sorted array of distinct positive integers, print all triplets that forms Geometric Progression with integral common ratio.
A geometric progression is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed, non-zero number called the common ratio. For example, the sequence 2, 6, 18, 54,… is a geometric progression with common ratio 3.
Input: arr = [1, 2, 6, 10, 18, 54] Output: 2 6 18 6 18 54 Input: arr = [2, 8, 10, 15, 16, 30, 32, 64] Output: 2 8 32 8 16 32 16 32 64 Input: arr = [ 1, 2, 6, 18, 36, 54] Output: 2 6 18 1 6 36 6 18 54
The idea is to start from the second element and fix every element as middle element and search for the other two elements in a triplet (one smaller and one greater). For an element arr[j] to be middle of geometric progression, there must exist elements arr[i] and arr[k] such that –
arr[j] / arr[i] = r and arr[k] / arr[j] = r where r is an positive integer and 0 <= i < j and j < k <= n - 1
Below is the implementation of above idea –
1 2 4 1 4 16
Time complexity of above solution is O(n2) as for every j, we are finding i and k in linear time.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find the missing number in Geometric Progression
- Print all triplets in sorted array that form AP
- Find maximum sum of triplets in an array such than i < j < k and a[i] < a[j] < a[k]
- Find number of triplets in array such that a[i]>a[j]>a[k] and i<j<k
- Find triplets in an array whose AND is maximum
- Find Kth number from sorted array formed by multiplying any two numbers in the array
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Find the index of first 1 in a sorted array of 0's and 1's
- Find the index of first 1 in an infinite sorted array of 0s and 1s
- Find first and last positions of an element in a sorted array
- Find the element that appears once in a sorted array
- Find the number of elements greater than k in a sorted array
- Given an absolute sorted array and a number K, find the pair whose sum is K
- Find the only repeating element in a sorted array of size n
- Find the minimum element in a sorted and rotated array