Count Elements With Maximum Frequency

Count Elements With Maximum Frequency

You are given an array nums consisting of positive integers.

Return the total frequencies of elements in nums such that those elements all have the maximum frequency.

The frequency of an element is the number of occurrences of that element in the array.

LeetCode Problem - 3005

class Solution {
    public int countWords(String[] words1, String[] words2) {
        // Variable to store the count of words appearing exactly once in both arrays
        int result = 0;
        // HashMap to store the frequency of words in words1
        HashMap<String, Integer> hm1 = new HashMap<>();
        // HashMap to store the frequency of words in words2
        HashMap<String, Integer> hm2 = new HashMap<>();

        // Count the frequency of words in words1
        for (String str : words1) {
            hm1.put(str, hm1.getOrDefault(str, 0) + 1);
        }
        // Count the frequency of words in words2
        for (String str : words2) {
            hm2.put(str, hm2.getOrDefault(str, 0) + 1);
        }

        // Iterate through each word in words1
        for (String word : words1) {
            // If the word appears exactly once in both words1 and words2, increment the result
            if (hm1.get(word) == 1 && hm2.getOrDefault(word, 0) == 1) {
                result++;
            }
        }

        // Return the count of words appearing exactly once in both arrays
        return result;
    }
}