<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) {
        unordered_set<long long> hashes;
        long long base = 31;
        long long mod = 1e15+2;
        long long finalPower = 1;
        for(int i=1; i<n; i++){
            finalPower = (finalPower * base)%mod;
        }
        long long rHash = 0;
        for(int i=0; i<n; i++){
            rHash = (rHash * base) % mod;
            rHash = (rHash + s[i] - 'a' +1)%mod;
        }
        hashes.insert(rHash);
        for(int j=n; j<s.size(); j++){
            rHash = (rHash - ((s[j-n] - 'a' + 1)*finalPower)%mod + mod)%mod;
            rHash = (rHash * base)%mod;
            rHash = (rHash + s[j] - 'a'+1)%mod;
            if(hashes.contains(rHash)){
                return s.substr(j-n+1, n);
            }
            hashes.insert(rHash);
        }
        return "";
    }

    string longestDupSubstring(string s) {
        unordered_set<long long> hashes;
        string result = "";
        int low = 1;
        int high = s.size()-1;
        while(low <= high){
            int mid = (low + high)/2;
            string temp = longestDupSubstring(s, mid);
            if(temp.size() > result.size()){
                result = temp;
            }
            if(temp.size() == 0){
                high = mid-1;
            } else{
                low = mid + 1;
            }
        }
        return result;
    }
};
210020