Find Common Characters

Find Common Characters

Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.

LeetCode Problem - 1002

class Solution {
    // Method to find common characters among an array of words
    public List<String> commonChars(String[] words) {
        // Create a HashMap to store the frequency of characters in the first word
        Map<Character, Integer> charFrequencyMap = new HashMap<>();
        // Iterate over the characters of the first word
        for (int i = 0; i < words[0].length(); i++) {
            // Update the frequency map
            charFrequencyMap.put(words[0].charAt(i), charFrequencyMap.getOrDefault(words[0].charAt(i), 0) + 1);
        }

        // Iterate over the remaining words
        for (int i = 1; i < words.length; i++) {
            // Create a frequency map for the current word
            Map<Character, Integer> currentFrequencyMap = new HashMap<>();
            // Iterate over the characters of the current word
            for (int j = 0; j < words[i].length(); j++) {
                // Update the frequency map
                currentFrequencyMap.put(words[i].charAt(j), currentFrequencyMap.getOrDefault(words[i].charAt(j), 0) + 1);
            }

            // Update the character frequency map based on common characters
            for (Character check : charFrequencyMap.keySet()) {
                if (currentFrequencyMap.containsKey(check) && charFrequencyMap.get(check) > 0) {
                    charFrequencyMap.put(check, Math.min(charFrequencyMap.get(check), currentFrequencyMap.get(check)));
                } else {
                    charFrequencyMap.put(check, 0);
                }
            }
        }

        // Create a list to store common characters
        List<String> result = new ArrayList<>();
        // Iterate over the characters in the frequency map
        for (Character key : charFrequencyMap.keySet()) {
            // Add common characters to the result list
            if (charFrequencyMap.get(key) > 0) {
                for (int i = 0; i < charFrequencyMap.get(key); i++) {
                    result.add(key + "");
                }
            }
        }

        // Return the list of common characters
        return result;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!