Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Count triplets #106

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions DSA/Python/Hashing/Count Triplets/Problem Statement
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
You are given an array and you need to find number of tripets of indices (i,j,k) such that the elements at those indices are in geometric progression for a given common ratio r and i<j<k .
Function Description

Complete the countTriplets function in the editor below.

countTriplets has the following parameter(s):

int arr[n]: an array of integers
int r: the common ratio
Returns

int: the number of triplets

Input Format

The first line contains two space-separated integers n and r, the size of arr and the common ratio.
The next line contains n space-seperated integers arr[i].
18 changes: 18 additions & 0 deletions DSA/Python/Hashing/Count Triplets/Solution
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from collections import Counter

def countTriplets(arr, r):
a = Counter(arr)
b = Counter()
s = 0
for i in arr:
j = i//r
k = i*r
a[i]-=1
if b[j] and a[k] and i%r == 0:
s+=b[j]*a[k]
b[i]+=1
return s

n,r = map(int,input().split())
arr = list(map(int,input().split()))
print(countTriplets(arr, r))