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

using ULL = uint64_t;
class Solution {
    string res = "";
public:
    string longestDupSubstring(string s) {
        int n = s.size();
        int l = 0;
        int r = n;
        while(l<=r){
            int mid = l+(r-l)/2;
            if(valid(s, mid)) l = mid+1;
            else r = mid-1;
        }
        return res;
    }

    bool valid(const string& s, const int len){
        ULL base = 27;
        unordered_set<ULL> seen;
        ULL base_len = 1;
        for(int i=0; i<len-1; i++) base_len *= base;
        ULL cur_hash = 0;
        for(int i=0; i<s.size(); i++){
            int cur = s[i]-'a';
            cur_hash = cur_hash*base + cur;

            if(i>=len-1){
                if(seen.find(cur_hash)!=seen.end()){
                    res = s.substr(i-len+1, len);
                    return true;
                }
                seen.insert(cur_hash);
                cur_hash -= (s[i-len+1]-'a')*base_len;
            }
        }
        return false;
    }
};
181220