- 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
- 53 lines of Java from the credited upstream file 1554-2.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 5 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 public boolean differByOne(String[] dict) {3 final int m = dict[0].length();4 int[] wordToHash = new int[dict.length];5 6 for (int i = 0; i < dict.length; ++i)7 wordToHash[i] = getHash(dict[i]);8 9 10 11 12 int coefficient = 1;13 for (int j = m - 1; j >= 0; --j) {14 Map<Integer, List<Integer>> newHashToIndices = new HashMap<>();15 for (int i = 0; i < dict.length; ++i) {16 final int newHash =17 (int) ((wordToHash[i] - (long) coefficient * val(dict[i].charAt(j)) % HASH + HASH) %18 HASH);19 if (newHashToIndices.containsKey(newHash)) {20 for (final int index : newHashToIndices.get(newHash)) {21 if (dict[i].substring(0, j).equals(dict[index].substring(0, j)) &&22 dict[i].substring(j + 1).equals(dict[index].substring(j + 1))) {23 return true;24 }25 }26 }27 newHashToIndices.putIfAbsent(newHash, new ArrayList<>());28 newHashToIndices.get(newHash).add(i);29 }30 coefficient = (int) (coefficient * BASE % HASH);31 }32 33 return false;34 }35 36 private static final long BASE = 26;37 private static final int HASH = 1_000_000_007;38 39 private static int val(char c) {40 return c - 'a';41 }42 43 44 45 private int getHash(String s) {46 int hash = 0;47 for (final char c : s.toCharArray()) {48 hash = (int) ((hash * BASE + val(c)) % HASH);49 }50 return hash;51 }52}53