<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 checkDup(string s, int len){
        long long M = 1e11+19;
        if (len <= 0)
            return "";
        int n = s.size();
        set<long long> hashset;
        long long hash = 0;
        for (int i = 0;i<len;i++){
            hash = ((hash * 31)%M + s[i] - 'a' + 1)%M;
        }
        //cout<<hash<<" ";
        hashset.insert(hash);
        long long val = 1;
        for (int i = 0;i<len-1;i++)
            val = (val * 31)%M;
        for (int i = len;i<n;i++){
            hash = (M + hash - ((s[i-len]-'a' + 1)*(val))%M)%M;
            //cout<<hash<<" ";
            hash = ((hash*31)%M + s[i] - 'a' + 1)%M;
            //cout<<hash<<" ";
            if (hashset.find(hash) != hashset.end())
                return s.substr(i - len + 1, len);
            hashset.insert(hash);
        }
        return "";
    }

    string longestDupSubstring(string s) {
        int n = s.size();
        int l = 0, r = n;
        while (l <= r){
            int m = (l+r)/2;
            //cout<<l<<" "<<r<<endl;
            if (checkDup(s, m) == "")
                r = m-1;
            else
                l = m+1;
        }
        return checkDup(s, r);
    }
};



244580