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

typedef long long int ll;
class Solution {
public:
    ll ind=-1, len=0;
    const ll mod = 1e9 + 7;
    vector<ll> pre, pre2;

    ll powermod(ll x, ll y, ll p){
        ll res = 1;
        while (y > 0) {
            if (y % 2 == 1)
                res = (res * x)%mod;
            y = y >> 1;
            x = (x * x)%mod;
        }
        return res % p;
    }

    ll inverse(ll n){
        // return 1ll;
        return powermod(n, mod-2, mod)%mod;
    }

    bool check(string &s, ll sz){
        ll n = s.size();

        map<pair<ll,ll>, ll> mp;
        mp[{pre[sz-1], pre2[sz-1]}]++;
        for(ll i = sz; i < n;i++){
            ll k = (pre[i] - pre[i-sz] + mod)%mod;
            ll kk = (pre2[i] - pre2[i-sz] + mod)%mod;

            k = (k*inverse(powermod(29, i-sz+1, mod)))%mod;
            kk = (kk*inverse(powermod(31, i-sz+1, mod)))%mod;

            mp[{k,kk}]++;
            if(mp[{k,kk}] >= 2){
                ind = i-sz+1;
                len = sz;
                return true;
            }
        }
        return false;
    }

    string longestDupSubstring(string s) {
        ll n = s.size();
        pre.resize(n);
        pre2.resize(n);
        for(ll i = 0; i < n;i++){
            pre[i] = ((s[i]-'a'+1)*powermod(29,i,mod))%mod;
            pre2[i] = ((s[i]-'a'+1)*powermod(31,i,mod))%mod;
            if(i){
                pre[i] = (pre[i] + pre[i-1])%mod;
                pre2[i] = (pre2[i] + pre2[i-1])%mod;
            }
        }
        ll l = 0, r = n+1; 
        while(r > l+1){
            ll mid = (l+r)/2;
            if(check(s,mid)){
                l = mid;
            }
            else{
                r = mid;
            }
        }
        string ans = "";
        if(ind==-1) return ans;
        for(int i = ind; i < ind+len;i++){
            ans += s[i];
        }
        return ans;
    }
};
325220