Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

1178. Number of Valid Words for Each Puzzle 🌟🌟🌟

With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:

Bit masking with hashmap

Code

class Solution
{
public:
    int maskWord(string word) // n|(1<<i) : set i'th bit
    {
        int mask = 0;
        for (auto c : word)
            mask |= (1 << c - 'a');
        return mask;
    }

    vector<int> findNumOfValidWords(vector<string> &words, vector<string> &puzzles)
    {
        vector<int> res;
        unordered_map<int, int> mask_freq; // map of bitmasks
        for (auto word : words)
            mask_freq[(maskWord(word))]++;

        for (auto puzzle : puzzles)
        {
            int mask = maskWord(puzzle), submask = mask;
            int first = (1 << puzzle[0] - 'a'), curr = 0;

            while (submask)
            {
                if (submask & first)
                    curr += mask_freq[submask];

                submask = (submask - 1) & mask;
            }

            res.push_back(curr);
        }
        return res;
    }
};

Interview Tips

Must Read: