<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

class Solution {
public:
    ull power[30010];
    ull hash[30010];
    int dubsubstr(string_view s, int m) {
        if (m == 0) return 0;
        
        unordered_map<ull, int> ma;
        for (int i = 0; i + m <= s.size(); ++i) {
            ull hs = hash[i+m] - hash[i] * power[m];
            if (auto it = ma.find(hs); it != ma.end()) {
                if (memcmp(s.data() + i, s.data() + it->second, m) == 0) {
                    return it->second;
                }
            }
            ma[hs] = i;
        }
        return -1;
    }
    string longestDupSubstring(string s) {
        int n = s.size();
        // Precomputations.
        ull base = 131;
        power[0] = 1;
        for (int i = 0; i < n; ++i) {
            power[i + 1] = power[i] * base;
            hash[i + 1] = hash[i] * base + s[i];
        }
        // Binary search on substring length.
        int hi = n, lo = 0;
        while (hi > lo) {
            int m = lo + (hi - lo) / 2;
            if (dubsubstr(s, m) == -1) hi = m;
            else lo = m + 1;
        }
        hi--;
        return s.substr(dubsubstr(s, hi), hi);
    }
};

const static auto speed_up = []() {
    std::ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    return 0;
}();
273380