Count Words Obtained After Adding a Letter — LeetCode 2135 Python Solution

MediumBit ManipulationArrayHash TableStringSorting
Problem
#2135
Reading time
2 min

The problem

You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.

Example

Input
startWords = ["ant","act","tack"], targetWords = ["tack","act","acti"]
Output
2
Explanation
- In order to form targetWords[0] = "tack", we use startWords[1] = "act", append 'k' to it, and rearrange "actk" to "tack".

Python solution

Python
class Solution:
    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:
        s = {sum(1 << (ord(c) - 97) for c in w) for w in startWords}
        ans = 0
        for w in targetWords:
            x = sum(1 << (ord(c) - 97) for c in w)
            for c in w:
                if x ^ (1 << (ord(c) - 97)) in s:
                    ans += 1
                    break
        return ans

Complexity

MeasureComplexity
TimeO(n \times |\Sigma|)
SpaceO(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2135. Count Words Obtained After Adding a Letter is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2135. Count Words Obtained After Adding a Letter?
LeetCode 2135. Count Words Obtained After Adding a Letter is rated Medium on LeetCode.
What is the time complexity of LeetCode 2135. Count Words Obtained After Adding a Letter?
The Python solution on this page runs in O(n \times |\Sigma|).
What is the space complexity of LeetCode 2135. Count Words Obtained After Adding a Letter?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2135. Count Words Obtained After Adding a Letter cover?
LeetCode 2135. Count Words Obtained After Adding a Letter is tagged Bit Manipulation, Array, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview