Find Common Characters

Find Common Characters

The problem asks us to find characters that appear in all strings, including duplicates.

Here’s the approach:

// Author: Tecker
// time: O(N)
// space: O(1)

vector<string> commonChars(vector<string>& A) {
    vector<string> res;
    vector<int> cnt(26, INT_MAX);
    int tmp[26]={0};
    for(auto s : A) {
        for(auto c : s) ++tmp[c-'a'];
        for(int j=0;j<26;++j) cnt[j] = min(cnt[j], tmp[j]);
        fill(tmp, tmp+26, 0);
    }

    for(int i=0;i<26;++i)
        for(int j=0;j<cnt[i];++j) res.push_back(string(1, i+'a'));
    return res;
}

The algorithm works like this:

  1. Keep track of character counts across all strings
  2. For each string, count its characters in tmp
  3. Update the global minimum count for each character
  4. After processing all strings, build the result from remaining counts

Time complexity is O(N) where N is total characters. Space is O(1) since we use fixed-size arrays.

#strings