LeetCode Solutions

1002. Find Common Characters

Time:

Space:

			

class Solution {
 public:
  vector<string> commonChars(vector<string>& A) {
    vector<string> ans;
    vector<int> commonCount(26, INT_MAX);

    for (const string& a : A) {
      vector<int> count(26);
      for (char c : a)
        ++count[c - 'a'];
      for (int i = 0; i < 26; ++i)
        commonCount[i] = min(commonCount[i], count[i]);
    }

    for (char c = 'a'; c <= 'z'; ++c)
      for (int i = 0; i < commonCount[c - 'a']; ++i)
        ans.push_back(string(1, c));

    return ans;
  }
};
			

class Solution {
  public List<String> commonChars(String[] A) {
    List<String> ans = new ArrayList<>();
    int[] commonCount = new int[26];
    Arrays.fill(commonCount, Integer.MAX_VALUE);

    for (String a : A) {
      int[] count = new int[26];
      for (char c : a.toCharArray())
        ++count[c - 'a'];
      for (int i = 0; i < 26; ++i)
        commonCount[i] = Math.min(commonCount[i], count[i]);
    }

    for (char c = 'a'; c <= 'z'; ++c)
      for (int i = 0; i < commonCount[c - 'a']; ++i)
        ans.add(String.valueOf(c));

    return ans;
  }
}
			

class Solution:
  def commonChars(self, A: List[str]) -> List[str]:
    ans = []
    commonCount = [math.inf] * 26

    for a in A:
      count = [0] * 26
      for c in a:
        count[ord(c) - ord('a')] += 1
      for i in range(26):
        commonCount[i] = min(commonCount[i], count[i])

    for c in string.ascii_lowercase:
      for j in range(commonCount[ord(c) - ord('a')]):
        ans.append(c)

    return ans