<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) {
        int n = s.size(), l = 0, r = n;
        
        power = vector<int>(n);
        for(int i = 0; i < n; i++)  power[i] = (i == 0) ? 1 : (power[i-1] * 26) % prime;
        
        string res;
        while(l <= r) {
            int mid = l + (r - l) / 2;
            string dup = rabinKarp(s, mid);
            
            if((int)dup.size() > (int)res.size()) {
                res = dup;
                l = mid+1;
            } else  r = mid-1;
        }
        return res;
    }
    
private:
    int prime = 10000007;
    vector<int> power;
    
    string rabinKarp(string s, int len) {
        if(len == 0)    return "";
        int n = s.size(), curr = 0;
        unordered_map<int, vector<int>> hash;
        
        for(int i = 0; i < len; i++) {
            curr = (curr * 26 + (s[i]-'a')) % prime;
        }
        hash[curr] = {0};  
        
        for(int i = len; i < n; i++) {
            curr = ((curr - power[len-1] * (s[i-len]-'a')) % prime + prime) % prime;
            curr = (curr * 26 + (s[i]-'a')) % prime;
            
            if(hash.find(curr) == hash.end())   hash[curr] = {i-len+1};
            else {
                for(int index: hash[curr]) {
                    if(s.substr(index, len) == s.substr(i-len+1, len))  return s.substr(index, len);
                }
                hash[curr].push_back({i-len+1});
            }
        }
        return "";      
    }
};
446180