- 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
- 68 lines of C++ from the credited upstream file 1044.cpp.
- The implementation visibly relies on sequence storage, hash 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:3 string longestDupSubstring(string s) {4 const int n = s.length();5 vector<int> pows(n, 1);6 int bestStart = -1;7 int l = 1;8 int r = n;9 10 for (int i = 1; i < n; ++i)11 pows[i] = pows[i - 1] * kBase % kHash;12 13 while (l < r) {14 const int m = (l + r) / 2;15 const 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.substr(bestStart, l - 1);28 return s.substr(bestStart, l);29 }30 31 private:32 static constexpr long kBase = 26;33 static constexpr int kHash = 1'000'000'007;34 35 static constexpr int val(char c) {36 return c - 'a';37 }38 39 40 int getStart(const string& s, int k, const vector<int>& pows) {41 unordered_map<int, vector<int>> hashToStarts;42 long h = 0;43 44 45 for (int i = 0; i < k; ++i)46 h = (h * kBase % kHash + val(s[i])) % kHash;47 hashToStarts[h].push_back(0);48 49 50 for (int i = k; i < s.length(); ++i) {51 const int startIndex = i - k + 1;52 h = ((h - static_cast<long>(pows[k - 1]) * val(s[i - k])) % kHash +53 kHash) %54 kHash;55 h = (h * kBase + val(s[i])) % kHash;56 if (const auto it = hashToStarts.find(h); it != hashToStarts.cend()) {57 const string currSub = s.substr(startIndex, k);58 for (const int start : it->second)59 if (s.substr(start, k) == currSub)60 return startIndex;61 }62 hashToStarts[h].push_back(startIndex);63 }64 65 return -1;66 }67};68