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.
Java solution that loops in forward direction. Thanks for the tips
privatestaticlongcountTriplets(List<Long>arr,longr){Map<Long,Long>potential=newHashMap<>();Map<Long,Long>counter=newHashMap<>();longcount=0;for(inti=0;i<arr.size();i++){longa=arr.get(i);longkey=a/r;if(counter.containsKey(key)&&a%r==0){count+=counter.get(key);}if(potential.containsKey(key)&&a%r==0){longc=potential.get(key);counter.put(a,counter.getOrDefault(a,0L)+c);}potential.put(a,potential.getOrDefault(a,0L)+1);// Every number can be the start of a triplet.}returncount;}
The a % r == 0 check is needed for cases where integer division would give a false positive. e.g given [5, 2, 15, 17, 45, 51] and r = 3. At index 3, we have 17 which after integer dividing by 3 we get 5 so that would lead to wrong triplet 5, 17, 51
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 →
Java solution that loops in forward direction. Thanks for the tips
The a % r == 0 check is needed for cases where integer division would give a false positive. e.g given [5, 2, 15, 17, 45, 51] and r = 3. At index 3, we have 17 which after integer dividing by 3 we get 5 so that would lead to wrong triplet 5, 17, 51