1569. One Letter Apart Sets

Medium3.5 points estimatedBitmaskHash TableStringCounting

A spelling game gives every player a word from the array words. Only the set of distinct letters of a word matters (order and repeats are ignored). Two players are neighbours if their letter sets differ by exactly one letter: one set is the other plus one extra letter, nothing else changing.

Count the pairs of positions i < j whose words are neighbours. Words with identical letter sets are not neighbours, and equal words at different positions are counted as different players. Return the count as a 64-bit integer.

Hint: turn each word into a 26-bit mask and count each mask in a hash map. For every mask and every set bit, multiply its count by the count of the mask with that bit removed; each neighbouring pair is then seen exactly once.

Required complexity: O(total length + 26 * distinct masks) time and O(distinct masks) space.

Example 1

Input:
words = ["ab","abc","b","bb"]
Output:
3
Explanation:

Sets {a,b} and {a,b,c} differ by c, and {a,b} differs from each of the two {b} words by a, giving 3 pairs.

Example 2

Input:
words = ["a","b","c"]
Output:
0
Explanation:

Any two of these sets differ by two letters, so no pair qualifies and the answer is 0.

Constraints

1 ≤ n ≤ 105 (n = words.length)

1 ≤ words[i].length ≤ 20

words[i] consists of lowercase English letters.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(L + 26 * W)
Space
O(W)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…