- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 37 lines of Python from the credited upstream file 1554-2.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def differByOne(self, dict: list[str]) -> bool:3 BASE = 264 HASH = 1_000_000_0075 m = len(dict[0])6 7 def val(c: str) -> int:8 return ord(c) - ord('a')9 10 def getHash(s: str) -> int:11 """Returns the hash of `s`. Assume the length of `s` is m.12 13 e.g. getHash(s) = 26^(m - 1) * s[0] + 26^(m - 2) * s[1] + ... + s[m - 1].14 """15 hash = 016 for c in s:17 hash = (hash * BASE + val(c))18 return hash19 20 wordToHash = [getHash(word) for word in dict]21 22 23 24 25 coefficient = 126 for j in range(m - 1, -1, -1):27 newHashToIndices = collections.defaultdict(list)28 for i, (word, hash) in enumerate(zip(dict, wordToHash)):29 newHash = (hash - coefficient * val(word[j]) % HASH + HASH) % HASH30 if any(word[: j] == dict[index][: j] and word[j + 1:] ==31 dict[index][j + 1:] for index in newHashToIndices[newHash]):32 return True33 newHashToIndices[newHash].append(i)34 coefficient = coefficient * BASE % HASH35 36 return False37