- 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
- 67 lines of Java from the credited upstream file 1044.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 String longestDupSubstring(String s) {3 final int n = s.length();4 int[] pows = new int[n];5 int bestStart = -1;6 int l = 1;7 int r = n;8 9 pows[0] = 1;10 for (int i = 1; i < n; ++i)11 pows[i] = (int) (pows[i - 1] * BASE % HASH);12 13 while (l < r) {14 final int m = (l + r) / 2;15 final int start = getStart(s, m, pows);16 if (start == -1) {17 r = m;18 } else {19 bestStart = start;20 l = m + 1;21 }22 }23 24 if (bestStart == -1)25 return "";26 if (getStart(s, l, pows) == -1)27 return s.substring(bestStart, bestStart + l - 1);28 return s.substring(bestStart, bestStart + l);29 }30 31 private static final long BASE = 26;32 private static final long HASH = 1_000_000_007;33 34 private static int val(char c) {35 return c - 'a';36 }37 38 39 private int getStart(final String s, int k, int[] pows) {40 Map<Long, List<Integer>> hashToStarts = new HashMap<>();41 long h = 0;42 43 44 for (int i = 0; i < k; ++i)45 h = (h * BASE % HASH + val(s.charAt(i))) % HASH;46 hashToStarts.put(h, new ArrayList<>());47 hashToStarts.get(h).add(0);48 49 50 for (int i = k; i < s.length(); ++i) {51 final int startIndex = i - k + 1;52 h = ((h - (long) (pows[k - 1]) * val(s.charAt(i - k))) % HASH + HASH) % HASH;53 h = (h * BASE + val(s.charAt(i))) % HASH;54 if (hashToStarts.containsKey(h)) {55 final String currSub = s.substring(startIndex, startIndex + k);56 for (final int start : hashToStarts.get(h))57 if (s.substring(start, start + k).equals(currSub))58 return startIndex;59 }60 hashToStarts.put(h, new ArrayList<>());61 hashToStarts.get(h).add(startIndex);62 }63 64 return -1;65 }66}67