Skip to content

2135. Count Words Obtained After Adding a Letter 👍

  • Time: $O(\Sigma |\texttt{startWords[i]}| + \Sigma |\texttt{targetWords[i]}|)$
  • Space: $O(\Sigma |\texttt{startWords[i]}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
 public:
  int wordCount(vector<string>& startWords, vector<string>& targetWords) {
    int ans = 0;
    unordered_set<int> seen;

    for (const string& w : startWords)
      seen.insert(getMask(w));

    for (const string& w : targetWords) {
      const int mask = getMask(w);
      for (const char c : w)
        // Toggle one character.
        if (seen.contains(mask ^ 1 << c - 'a')) {
          ++ans;
          break;
        }
    }

    return ans;
  }

 private:
  int getMask(const string& s) {
    int mask = 0;
    for (const char c : s)
      mask ^= 1 << c - 'a';
    return mask;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public int wordCount(String[] startWords, String[] targetWords) {
    int ans = 0;
    Set<Integer> seen = Arrays.stream(startWords).map(this::getMask).collect(Collectors.toSet());

    for (final String w : targetWords) {
      final int mask = getMask(w);
      for (final char c : w.toCharArray())
        // Toggle one character.
        if (seen.contains(mask ^ 1 << c - 'a')) {
          ++ans;
          break;
        }
    }

    return ans;
  }

  private int getMask(final String s) {
    int mask = 0;
    for (final char c : s.toCharArray())
      mask ^= 1 << c - 'a';
    return mask;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def wordCount(self, startWords: list[str], targetWords: list[str]) -> int:
    def getMask(s: str) -> int:
      mask = 0
      for c in s:
        mask ^= 1 << string.ascii_lowercase.index(c)
      return mask

    ans = 0
    seen = set(getMask(w) for w in startWords)

    for targetWord in targetWords:
      mask = getMask(targetWord)
      for c in targetWord:
        # Toggle one character.
        if mask ^ 1 << string.ascii_lowercase.index(c) in seen:
          ans += 1
          break

    return ans