1240. One-Off Word Pairs

Medium3.5 points estimatedHash TableStringCounting3 hints

A spell checker wants to find typos that are a single wrong letter away from another entry. Given the array words of lowercase words, count the index pairs i < j such that words[i] and words[j] have the same length and differ in exactly one position. Identical words differ in zero positions, so they never form a pair, and words of different lengths never do either. Duplicates in the array are allowed and are counted by index.

Return the number of such pairs as a long. A direct comparison of all pairs is too slow in general; instead replace one position of every word by a wildcard, count each masked key in a hash map, and correct for identical words, which share every masked key.

The intended solution runs in O(n * L) time and O(n * L) space for n words of length at most L.

Example 1

Input:
words = ["cat","bat","cot","dog"]
Output:
2
Explanation:

cat differs from bat and from cot in exactly one position, while bat and cot differ in two and dog differs from all three in every position.

Example 2

Input:
words = ["aa","aa","ab"]
Output:
2
Explanation:

Each copy of aa differs from ab in one position, giving two pairs; the two identical aa words form no pair.

Constraints

1 ≤ words.length ≤ 2000

1 ≤ words[i].length ≤ 10

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.

Expected complexity

Time
O(n * L)
Space
O(n * L)

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…