<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 ll long long
#define MOD 1000000007

struct Hash {
    const ll BASE1 = 5689;
    const ll BASE2 = 8861;
    vector<pair<ll, ll>> hashes, Pow;

    Hash(string s) {
        hashes.assign(s.size() + 1, {1, 1});
        Pow.assign(s.size() + 1, {1, 1});
        
        for (int i = 0; i < s.size(); ++i) {
            hashes[i + 1] = { 
                (hashes[i].first * BASE1 + (s[i] - 'a' + 1)) % MOD,
                (hashes[i].second * BASE2 + (s[i] - 'a' + 1)) % MOD 
            };
            Pow[i + 1] = { 
                (Pow[i].first * BASE1) % MOD,
                (Pow[i].second * BASE2) % MOD 
            };
        }
    } 
    
    pair<ll, ll> get(ll l, ll r) {
        ++l; ++r; // Convert to 1-based indexing
        ll hash1 = (hashes[r].first - (hashes[l - 1].first * Pow[r - l + 1].first) % MOD + MOD) % MOD;
        ll hash2 = (hashes[r].second - (hashes[l - 1].second * Pow[r - l + 1].second) % MOD + MOD) % MOD;
        return {hash1, hash2};
    }
};

class Solution {
public:
    string longestDupSubstring(string s) {
        Hash a(s);
        int left = 1, right = s.size(), len = 0, index = -1;

        auto ok = [&](int len) {
            map<pair<ll, ll>, int> m;
            int local_index = -1;
            for (int i = 0; i + len - 1 < s.size(); ++i) {
                pair<ll, ll> current_hash = a.get(i, i + len - 1);
                if (++m[current_hash] >= 2) local_index = i;
            }
            return local_index;
        };

        while (left <= right) {
            int mid = (left + right) / 2;
            int ind = ok(mid);
            if (ind != -1) {
                index = ind;
                len = mid;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return (index != -1) ? s.substr(index, len) : "";
    }
};
365540