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.
public static int beautifulPairs(List A, List B) {
// Write your code here
//frequency map for A
Map freqMapA = A.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// frequency map for B
Map<Integer, Long> freqMapB = B.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// iterate over A's frequency map, filter those are in B only. get min
// of both the frequency, that will be count of pairs for that number
int count = freqMapA.entrySet().stream().filter(en -> freqMapB.containsKey(en.getKey())).map(en -> Math.min(en.getValue(), freqMapB.get(en.getKey()))).mapToInt(Long::intValue).sum();
// adjust count since we're to update one index
return count == A.size() ? count - 1 : count + 1;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Beautiful Pairs
You are viewing a single comment's thread. Return to all comments →
Here's my java solution
public static int beautifulPairs(List A, List B) { // Write your code here //frequency map for A Map freqMapA = A.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));