The Indian Engineer

Problem 1002 Find Common Characters

Posted on Last edited 2 mins

String Hash-Table Vector Array

Problem Statement

Link - Problem 1002

Question

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.

Example 1

Input: words = ["bella","label","roller"]
Output: ["e","l","l"]

Example 2

Input: words = ["cool","lock","cook"]
Output: ["c","o"]

Constraints

Solution

class Solution {
public:
    vector<string> commonChars(vector<string>& words) {
        vector<int>baselineCount(26,0);
        string temp;
        for(int i =0;i<words[0].size();i++)
            {
                baselineCount[words[0][i]-'a']++;
            }
        for(auto word:words)
        {
            vector<int>newCount(26,0);
            for(const auto& ch:word)
                newCount[ch-'a']++;

            for(int i= 0;i<26;i++)
                baselineCount[i] = min(baselineCount[i],newCount[i]);
        }
        vector<string>answer;
        for(int i =0; i<26;i++)
        {
            while(baselineCount[i]--)
            {
                temp = "";
                temp += 'a'+i;
                answer.push_back(temp);
            }
        }
        return answer;


    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

This problem is about finding the common characters in a given set of strings.