<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 {
    int len;
    int pos;    
public:
    string longestDupSubstring(string s) {
        int n = s.size();
        int l = 1;
        int r = n;
        len = 0;
        pos = -1;
        while(l<=r){
            int mid = l+(r-l)/2;
            if(valid(s, mid)) l = mid+1;
            else r = mid-1;
        }
        if(pos==-1) return "";
        return s.substr(pos, len);
    }

    bool valid(const string& s, int k){
        int n = s.size();
        unordered_set<ULL> seen;
        ULL key = 0;
        ULL base = 27;
        ULL base_k = 1;
        for(int i=0; i<k; i++) base_k *= base;
        for(int i=0; i<n; i++){
            key = key*base + (s[i]-'a');
            if(i>=k) key = key - base_k*(s[i-k]-'a');
            if(i>=k-1){
                if(seen.count(key)){
                    len = k;
                    pos = i-len+1;
                    return true;
                }
                seen.insert(key);
            }
        }
        return false;
    }
};
186980