We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
funccountTriplets(arr[]int64,rint64)int64{varcint64// Will contain the right hand side of the triplet.// We only care about the number of times it appears because we only need to calculate permutations.rightFreqMap:=make(map[int64]int64)// Will contain the left hand side of the triplet.// We only care about the number of times it appears because we only need to calculate permutations.leftFreqMap:=make(map[int64]int64)// Loop the arr to fill the right hand side frequencies.for_,v:=rangearr{rightFreqMap[v]++}// Handle a special case where r == 1 where the triplets are calculated by using the combinations without repetition formula (n!/k!(n-k)!)ifr==1{for_,freq:=rangerightFreqMap{c+=freq*(freq-1)*(freq-2)/6}returnc}// Loop the array where the selected element is considered the middle of the triplet.fori:=0;i<len(arr);i++{mid:=arr[i]// Perform calculations only if the mid can be divided by r.ifmid%r==0{left:=mid/rleftFreq:=leftFreqMap[left]right:=mid*rrightFreq:=rightFreqMap[right]// Here we need to calculate the number of permutations for 1 mid, leftFreq and rightFreq which is 1 * leftFreq * rightFreq.// If right or mid are not present in the map, leftFreqMap[left]==0 which adds nothing to the final result.c+=leftFreq*rightFreq}// Move the element from the right to the left frequency map.rightFreqMap[mid]--leftFreqMap[mid]++}returnc}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Count Triplets
You are viewing a single comment's thread. Return to all comments →
Here is mine in Go.