(interesting one) 1002. Find Common Characters

class Solution {
    public List<String> commonChars(String[] words) {

        int[] intersection = new int[26];
        boolean setIntesection = false;
        for (int i = 0; i < words.length; i++) {
            int[] count = new int[26];
            for (char c : words[i].toCharArray()) {
                count[c - 'a']++;
            }
            if (i == 0) {
                for (int j = 0; j < 26; j++) {
                    intersection[j] = count[j];
                }
            } else {
                findIntersection(intersection, count);
            }
        }
        List<String> result = new ArrayList<>();
        for (int i = 0; i < 26; i++) {
            if (intersection[i] > 0) {
                for (int j = 0; j < intersection[i]; j++) {
                    result.add(String.valueOf((char)(i+'a')));
                }
            }
        }
        return result;
    }
    private void findIntersection(int[] intersection, int[] count) { // key is to find the minimum common count (intersection count)
        for (int i = 0; i < 26; i++) {
            intersection[i] = Math.min(intersection[i], count[i]);
        }
    }
}

/**
T: O(words' len)
S: O(chars in word)
 */

Last updated