Strings Differ by One Character Problem
Description
LeetCode Problem 1554.
Given a list of strings dict where all the strings are of the same length.
Return true if there are 2 strings that only differ by 1 character in the same index, otherwise return false.
Example 1:
Input: dict = ["abcd","acbd", "aacd"]
Output: true
Explanation: Strings "abcd" and "aacd" differ only by one character in the index 1.
Example 2:
Input: dict = ["ab","cd","yz"]
Output: false
Example 3:
Input: dict = ["abcd","cccc","abyd","abab"]
Output: true
Constraints:
- The number of characters in
dict <= 10^5 dict[i].length == dict[j].lengthdict[i]should be unique.dict[i]contains only lowercase English letters.
Solution
Approach: Rolling Hash with One Position Blanked Out
Two different strings of the same length differ in exactly one position j if and only if they become equal once position j is ignored. So for each position j, we want to know whether two words agree everywhere except at j.
Building every "word with position j replaced by *" as a new string would cost O(m) per word and position, O(n * m2) in total, which is too slow for one or two very long words. A polynomial hash avoids that:
- Compute
h = c0 * B^(m-1) + c1 * B^(m-2) + ... + c(m-1)(mod a large prime) for every word once. - The hash of the word with position
jblanked out ish - c_j * B^(m-1-j), computed in O(1).
For each position j, put these masked hashes into a hash map. When a masked hash has been seen before, compare the two words directly (ignoring position j) to rule out a hash collision; if they match, return true. Because all words are distinct, two words with equal masked strings really do differ in exactly position j.
The base and modulus are chosen so that every product stays well below 253, which keeps the JavaScript version exact with plain numbers.
Complexity: O(n * m) expected time (collisions are rare, and each check is O(m)) and O(n) extra space per position, where n is the number of words and m their length.
class Solution:
def differByOne(self, dict: List[str]) -> bool:
MOD, BASE = 1000000007, 27
n, m = len(dict), len(dict[0])
# h[i]: polynomial hash of dict[i], first character most significant
h = [0] * n
for i, word in enumerate(dict):
for ch in word:
h[i] = (h[i] * BASE + ord(ch) - 96) % MOD
power = 1 # BASE ** (m - 1 - j)
for j in range(m - 1, -1, -1):
seen = {} # hash of a word with position j blanked out -> indexes of those words
for i, word in enumerate(dict):
masked = (h[i] - (ord(word[j]) - 96) * power) % MOD
for k in seen.get(masked, []):
# Equal hashes almost always mean equal strings, but check to rule out a collision.
if dict[k][:j] == word[:j] and dict[k][j + 1:] == word[j + 1:]:
return True
seen.setdefault(masked, []).append(i)
power = power * BASE % MOD
return False