Beautiful Pairs

  • + 0 comments

    My Java solution with linear time complexity and linear space complexity:

    public static int beautifulPairs(List<Integer> A, List<Integer> B) {
            // create a frequency map to get the count of eacg val
            Map<Integer, Integer> freqMap = new HashMap<>();
            for(int val : A) freqMap.put(val, freqMap.getOrDefault(val, 0) + 1);
            //iterate over each val in b and accoridngly increment the amt of pairs
            int pairs = 0;
            for(int val : B){
                if(freqMap.containsKey(val) && freqMap.get(val) > 0){
                    pairs++;
                    freqMap.put(val, freqMap.getOrDefault(val, 0) - 1);
                }
            }
            //if amt of pairs == a.size(), decrease it because by 1 bc an element must be changed
            //else add 1 bc an element isnt paired
            return (pairs == A.size()) ? pairs - 1 : pairs + 1;
        }