<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:
    vector<long long> v;
    long long mod=1e9+9,p=30;
    int cal(int n,string s,int k){
        unordered_map<int,int> m;
        long long hash=0;
        for(int j=0;j<n;j++){
            hash=((hash*p)%mod+(s[j]-'a'))%mod;
            if(j>=k){
                hash=(hash-(((s[j-k]-'a')*v[k])%mod)+mod+mod)%mod;
            }
            if(j>=(k-1)){
                if(m.find(hash)!=m.end()){
                    int u=j-k+1,v=m[hash],flag=1;
                    for(int y=0;y<k;y++){
                        if(s[u+y]!=s[v+y]){
                            flag=0;
                            break;
                        }
                    }
                    if(flag){
                        return j-k+1;
                    }
                }else{
                    m[hash]=j-k+1;
                }
            }
        }
        return -1;
    }
    string longestDupSubstring(string s) {
        int n=s.size();
        v.resize(n);
        v[0]=1;
        for(int i=1;i<n;i++){
            v[i]=(v[i-1]*p)%mod;
        }
        int l=1,r=n-1;
        while(l<r){
            int mid=(l+r+1)/2;
            if(cal(n,s,mid)!=-1){
                l=mid;
            }else{
                r=mid-1;
            }
        }
        int val=cal(n,s,l);
        if(val!=-1){
            string ans="";
            for(int i=val;i<(val+l);i++){
                ans+=s[i];
            }
            return ans;
        }
        return "";
    }
};
233060