<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 prime=1e9+7;
    vector<long long>power;
    string ans="";
    
    string longestDupSubstring(string s) {
        int n=s.length();
        power=vector<long long>(n,1);
        for(int i=1;i<n;i++){
            power[i]=(power[i-1]*26)%prime;
        }
        int low=0,high=n;
        while(low<=high){
            int mid=low+(high-low)/2;
            string tmp=validate(mid,s);
            if(tmp.length()==0){
                high=mid-1;
            }else{
                if(tmp.length()>ans.length()){
                    ans=tmp;
                }
                low=mid+1;
            }
        }
        return ans;
    }
    
    string validate(int mid,string s){
        if(mid==0) return "";
        string str=s;
        unordered_map<int,vector<int>>hash;
        long long cur=0;
        int i;
        for(int i=0;i<mid;i++){
            cur=((cur*26)%prime+(str[i]-'a'))%prime;
        }
        hash[cur]=vector<int>(1,0);
        int n=str.length();
        for(int i=mid;i<n;i++){
            cur=((cur-(long long)power[mid-1]*(str[i-mid]-'a'))%prime+prime)%prime;
            cur=(cur*26+(str[i]-'a'))%prime;
            if(hash.find(cur)==hash.end()){
                hash[cur]=vector<int>(1,i-mid+1);
            }else{
                for(auto x:hash[cur]){
                    if(str.substr(x,mid)==str.substr(i-mid+1,mid))
                        return str.substr(x,mid);
                }
                hash[cur].push_back(i-mid+1);
            }
        }
        return "";
    } 
};
440420