Beautiful Pairs

  • + 0 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()));

        // 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;
    }