<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:
    string longestDupSubstring(string s) {
        //#define int unsigned long long 
        int n=s.size();
        int p=1e9+7;
        int p1=998244353;
        mt19937_64 rng(time(0));
        //int x=rng()%p;
        int x=31;
        vector<int>h(n),h1(n),pow(n),pow1(n);
        h[0]=(s[0]-'a'+1);
        pow[0]=1;
        for(int i=1;i<n;i++){
            h[i]=((1LL*h[i-1]*x)%p+s[i]-'a'+1)%p;
            pow[i]=(1LL*pow[i-1]*x)%p;
        }
        h1[0]=(s[0]-'a'+1);
        pow1[0]=1;
        for(int i=1;i<n;i++){
            h1[i]=((1LL*h1[i-1]*x)%p1+s[i]-'a'+1)%p1;
            pow1[i]=(1LL*pow1[i-1]*x)%p1;
        }
        
        int lo=1,hi=n-1,ans=0,i1=-1;
        while(lo<=hi){
            int mid=(lo+hi)>>1;
            //to check every mid length string
            map<pair<int,int>,int>mp;
            for(int i=0;i<n;i++){
                if(i+mid-1>=n)break;
                int val=((h[i+mid-1]-((i==0)?0:((1LL*h[i-1]*pow[mid])%p)))%p+p)%p;
                int val1=((h1[i+mid-1]-((i==0)?0:((1LL*h1[i-1]*pow1[mid])%p1)))%p1+p1)%p1;
                mp[{val,val1}]++;
            }
            int t=0,l=-1,l1=-1;
            for(auto v:mp){
                if(v.second>1){
                    t=1;
                    l=v.first.first;
                    l1=v.first.second;
                    break;
                }
            }
            if(t){
                for(int i=0;i<n;i++){
                    if(i+mid-1>=n)break;
                    int val=((h[i+mid-1]-((i==0)?0:((1LL*h[i-1]*pow[i+mid-1-i+1])%p)))%p+p)%p;
                    int val1=((h1[i+mid-1]-((i==0)?0:((1LL*h1[i-1]*pow1[i+mid-1-i+1])%p1)))%p1+p1)%p1;
                    if(val==l&&val1==l1){
                        i1=i;break;
                    }
                }
                ans=mid;
                lo=mid+1;
            }
            else hi=mid-1;
        }
        //cout<<ans<<endl;
       // # undef int
        if(ans==0)return "";
        return s.substr(i1,ans);
    }
};
267620