Count Triplets hackerRank Solution: Looking for Count Triplets solution for Hackerrank problem? Get solution with source code and detailed explainer video.
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).
Go to problem statement
Explanation Video:
Youtube Channel partner: CodingCart
Mentor: Satyendra Jaiswal
Langauge: Python
Source Code: for countTriplets
function
# Complete the countTriplets function below.
def countTriplets(arr, r):
count=0
bef={}
aft={}
for v in arr:
if v in aft:
aft[v]+=1
else:
aft[v]=1
for v in arr:
aft[v]-=1 #current
if v//r in bef and v %r ==0 and v*r in aft:
count+=bef[v//r]*aft[v*r]
if v in bef:
bef[v]+=1
else:
bef[v]=1
return count
coming soon…
coming soon…
Full Source Code: countTriplets HackerRank Solution
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countTriplets function below.
def countTriplets(arr, r):
count=0
bef={}
aft={}
for v in arr:
if v in aft:
aft[v]+=1
else:
aft[v]=1
for v in arr:
aft[v]-=1 #current
if v//r in bef and v %r ==0 and v*r in aft:
count+=bef[v//r]*aft[v*r]
if v in bef:
bef[v]+=1
else:
bef[v]=1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
coming soon…
coming soon…
Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our Youtube Channel.
This post is in partner with CodingCart.