<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>

using lli = long long;

struct hasher {

    lli sz;
    lli p, mod;
    vector<lli> pk, fHash;

    void init(const string& s, lli _p, lli _mod) {
        sz = s.length();
        p = _p;
        mod = _mod;
        pk.resize(sz);
        fHash.resize(sz);

        pk[0] = 1;
        fHash[0] = s[0] - 'a' + 1;

        for (lli i = 1; i < sz; i++) {
            pk[i] = (pk[i - 1] * p) % mod;
            fHash[i] = (fHash[i - 1] * p + s[i] - 'a' + 1) % mod;
        }
    }

    lli getHash(lli l, lli r) {
        if (l == 0) return fHash[r];
        else return (fHash[r] - fHash[l - 1] * pk[r - l + 1] % mod + mod) % mod;
    }
};

string findduplicates(const string& s, lli x, hasher& hash) {
    unordered_set<lli> st;
    for (lli i = 0; i + x <= s.length(); i++) {
        lli cur_hash = hash.getHash(i, i + x - 1);
        if (st.count(cur_hash)) {
            return s.substr(i, x);
        }
        st.insert(cur_hash);
    }
    return "";
}

class Solution {
public:
    string longestDupSubstring(string s) {

        lli n = s.size();
        hasher hash1,hash2;
        hash1.init(s, 37 ,999999937);
        hash2.init(s, 31 ,1e9+7);

        lli lo = 1;
        lli hi = n;
        string ans = "";
        while (lo <= hi) {
            lli mid = lo + (hi - lo) / 2;
            string dup1 = findduplicates(s, mid, hash1);
            string dup2 = findduplicates(s, mid, hash2);
            
            if (!dup1.empty() && !dup1.empty() && dup1==dup2) {
                ans = dup1;
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }
        return ans;
    }
};

400100