<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 {
    const int BASE = 101;
    const int MOD = 1e9 + 7;

    string rabinKarp(string s, int len) {
        if (len == 0)
            return "";

        int n = s.size();
        long long currHash = 0;
        long long power = 1;
        unordered_map<long long, vector<int>> mp;

        // Precompute BASE^(len-1) % MOD for sliding window
        for (int i = 0; i < len - 1; ++i) {
            power = (power * BASE) % MOD;
        }

        for (int i = 0; i < len; ++i) {
            currHash = (currHash * BASE + (s[i] - 'a' + 1)) % MOD;
        }
        mp[currHash] = {0};

        for (int i = len; i < n; ++i) {

            int hash_start_pos = i - len + 1;

            int first_char = (s[i - len] - 'a' + 1);
            int next_char = (s[i] - 'a' + 1);

            int first_char_hash = (power * first_char) % MOD;

            currHash = (currHash - first_char_hash + MOD) % MOD;

            currHash = (currHash * BASE + next_char) % MOD;

            if (mp.find(currHash) != mp.end()) {

                auto cur_sub = s.substr(hash_start_pos, len);

                for (int index : mp[currHash]) {
                    auto sub = s.substr(index, len);

                    if (sub == cur_sub)
                        return sub;
                }
            }

            mp[currHash].push_back(hash_start_pos);
        }
        return "";
    }

public:
    string longestDupSubstring(string s) {
        int n = s.size();
        int start = 1, end = n - 1;

        string ans;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            string candidate = rabinKarp(s, mid);

            if (candidate.size() > ans.size()) {
                ans = candidate;
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return ans;
    }
};
434660