Leetcode 2256 Solution

This article provides solution to leetcode question 2256 (count-words-obtained-after-adding-a-letter)

https://leetcode.com/problems/count-words-obtained-after-adding-a-letter

Solution

class Solution:
    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:
        def get_word_mask(word):
            mask = 0
            for ch in word:
                mask |= 1 << (ord(ch) - ord('a'))
            return mask

        targetset = set()

        for word in startWords:
            targetset.add(get_word_mask(word))

        ans = 0
        for word in targetWords:
            target_word_mask = get_word_mask(word)

            for i in range(26):
                if target_word_mask & (1 << i) == 0:
                    continue

                if (target_word_mask ^ (1 << i)) in targetset:
                    ans += 1
                    break
        return ans