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

#define p 10000007
class Solution {
     string solve (string s, int len){
        if(len == 0) return "";
        unordered_map<int, vector<int>> hash;
        long long t = 0;
        long long M = 1e9+7;
        long long k = 1;
        for(int i = 0; i < len; i++) k = (k*10)%M;
        
        for(int i = 0; i < len; i++){
            t = ((t*10) % M  + (s[i] - 'a')) % M;
        }
        hash[t].push_back(0);
        for(int i = len; i < s.size(); i++){
            t = (t*10 - (k*(s[i-len]-'a'))%M + s[i]-'a' + M) % M;
            
            if(hash.find(t) != hash.end()){
                for(auto x : hash[t]){
                    if(s.substr(x,len) == s.substr(i-len+1,len)){
                        return s.substr(x,len);
                    }
                }
            }
            hash[t].push_back(i-len+1); 
            
        }
        return "";
    }
public:
    string longestDupSubstring(string s) {
        int n = s.size();
        if(n == 0) return "";
        string ans = "";
        int l = 0, r = n;
        while(l <= r){
            int len = (l+r)/2;
            if(solve(s, len).size() == len){
                l = len+1;
                ans=solve(s,len);
            }
            else r = len - 1;
        }
        return ans;
        
    }
};
469220