<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) {
        size_t len = s.length();
        int p = 31;
        vector<unsigned long long> c(len, 0);
        c[0] = 1;
        for(int i = 1; i < len; i++)
            c[i] = (c[i-1] * p);
        
        vector<unsigned long long> h(len+1, 0);
        for(int i = 0; i < len; i++)
            h[i+1] = (h[i] + (s[i]-'a'+1)*c[i]);
        
        int st = 0, mxlen = 0;
        int rmax = len-1, rmin = 1;
        while(rmin <= rmax){
            int m = (rmax+rmin)/2;
            unordered_set<unsigned long long> ss;
            bool match = false;
            for(int j = 0; j+m <= len; j++){
                unsigned long long hs = (h[j+m]-h[j])*c[len-m-j];
                if(ss.find(hs) != ss.end()){
                    st = j;
                    mxlen = m;
                    match = true;
                    break;
                } else ss.insert(hs);
            }
            if(match){
                rmin = m+1;
            } else rmax = m-1;
        }
        if(mxlen) return s.substr(st, mxlen);
        else return ""; 
    }
};
215780