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

#define ull unsigned long long
const ull MOD = 1e11 + 7;

ull hashs(const string &s, int st, int len, ull pr, const vector<ull> &pow) {
    ull hash = 0;
    for (int i = 0; i < len; ++i) {
        hash = (hash * pr + s[st + i]) % MOD;
    }
    return hash;
}

string check(const string &s, int len, ull pr) {
    if (len == 0) return "";
    unordered_set<ull> seen;
    ull hash = 0;
    int n = s.size();
    vector<ull> pow(n, 1);
    
    for (int i = 1; i < n; ++i) {
        pow[i] = (pow[i - 1] * pr) % MOD;
    }
    
    for (int i = 0; i <= n - len; ++i) {
        if (i == 0) {
            hash = hashs(s, i, len, pr, pow);
        } else {
            hash = (hash * pr % MOD - s[i - 1] * pow[len] % MOD + s[i + len - 1] + MOD) % MOD;
        }
        if (seen.count(hash)) {
            return s.substr(i, len);
        }
        seen.insert(hash);
    }
    return "";
}

class Solution {
public:
    string longestDupSubstring(string s) {
        int left = 1, right = s.size() - 1;
        string result = "";
        ull pr = 31;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            string cand = check(s, mid, pr);
            if (!cand.empty()) {
                result = cand;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }
};
250340