<p>Given a string <code>s</code>, consider all <em>duplicated substrings</em>: (contiguous) substrings of s that occur 2 or more times.&nbsp;The occurrences&nbsp;may overlap.</p>

<p>Return <strong>any</strong> duplicated&nbsp;substring that has the longest possible length.&nbsp;If <code>s</code> does not have a duplicated substring, the answer is <code>&quot;&quot;</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "banana"
<strong>Output:</strong> "ana"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "abcd"
<strong>Output:</strong> ""
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    long long suffixHash1[100005], suffixHash2[100005] = {0};
    const long long MOD = 1e9 + 7;
    const long long BASE1 = 993319, BASE2 = 919393;
    string longestDupSubstring(string s) {
        initSuffixHash(s);

        int l = 1, r = s.size();
        string ans = "";
        while(l <= r) {
            int mid = (l+r)/2;
            
            map<pair<int,int>,int>hashFrequency;
            hashFrequency.clear();
            bool found = false;
            for (int i = 0; i + mid <= s.size(); i++) {
                pair<int,int> curRangeHash = getRangeHash(i, i+mid-1);
                hashFrequency[curRangeHash]++;
                if (hashFrequency[curRangeHash] >= 2) {
                    ans = s.substr(i, mid);
                    found = true;
                    break;
                }
            }
            if (!found) {
                r = mid-1;
            } else {
                l = mid+1;
            }
        }

        return ans;
    }

    void initSuffixHash(string s) {
        for (int i = s.size()-1; i >= 0; i--) {
            suffixHash1[i] = ((suffixHash1[i+1]*BASE1)%MOD + s[i]-'a' + 1)%MOD;
            suffixHash2[i] = ((suffixHash2[i+1]*BASE2)%MOD + s[i]-'a' + 1)%MOD;
        }
    }

    pair<int,int> getRangeHash(int l, int r) {
        return {((suffixHash1[l] - (suffixHash1[r+1] * exp(BASE1, r-l+1))%MOD) + MOD)%MOD, ((suffixHash2[l] - (suffixHash2[r+1] * exp(BASE2, r-l+1))%MOD) + MOD)%MOD};
    }

    long long exp(int base, int power) {
        long long ans = 1;
        while(power > 0) {
            if (power&1) ans = (ans * base)%MOD;
            power /= 2;
            base = (1LL * base * base)%MOD;
        }
        return ans;
    }
};
233060