<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 {
private:
    int mod;
    int rollingHash(string& s, int len) {
        // stores hash key and starting index
        if (len >= s.size())
            return false;
        unordered_map<int, vector<int>> ump;
        long long cur = 0, h = 1;
        for (int i = 0; i < len; i++) {
            cur = (cur * 26 + (s[i] - 'a')) % mod;
            h = (h * 26) % mod;
        }
        ump[cur].push_back(0);
        for (int i = 1; i < s.size() - len + 1; i++) {
            cur = ((cur * 26 - h * (s[i - 1] - 'a') % mod) % mod + mod) % mod;
            cur = (cur + (s[i + len - 1] - 'a')) % mod;
            if (ump.find(cur) != ump.end()) {
                string s1 = s.substr(i, len);
                for (int idx : ump[cur]) {
                    string s2 = s.substr(idx, len);
                    if (s1 == s2)
                        return idx;
                }
            }
            ump[cur].push_back(i);
        }
        return -1;
    }

public:
    string longestDupSubstring(string s) {
        // binary search on monotonic fn, fn is rolling hash (rabin-karp)
        mod = 1e9 + 7;
        string res = "";
        int low = 0, high = s.size() - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            int cur = rollingHash(s, mid);
            if (cur == -1) {
                high = mid - 1;
            } else {
                res = s.substr(cur, mid);
                low = mid + 1;
            }
        }
        return res;
    }
};
417380