<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:
    std::string longestDupSubstring(const std::string& s) {
        constexpr ull BASE = 29;
        constexpr ull MOD = 1e9 + 7;
        int n = s.length();
        std::vector<int> nums(n);
        for (int i = 0; i < n; ++i)
            nums[i] = s[i] - 'a';

        int left = 1, right = n - 1;
        int start = -1, length = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            int st = search(mid, BASE, MOD, n, nums);
            if (st == -1) {
                right = mid - 1;
            } else {
                start = st;
                length = mid;
                left = mid + 1;
            }
        }
        return (start != -1) ? s.substr(start, length) : "";
    }

    int search(int L, int base, ull mod, int n, const std::vector<int>& nums) {
        ull h = 0;
        for (int i = 0; i < L; ++i)
            h = (h * base + nums[i]) % mod;
        
        std::unordered_map<ull, std::vector<int>> seen;
        seen[h].emplace_back(0);

        ull shiftLeft = 1;
        for (int i = 1; i <= L; ++i) {
            shiftLeft = (shiftLeft * base) % mod;
        }

        for (int i = 1; i <= n - L; ++i) {
            h = (h * base - nums[i - 1] * shiftLeft % mod + mod) % mod;
            h = (h + nums[i + L - 1]) % mod;

            if (seen.find(h) != seen.end()) {
                for (int start : seen[h]) {
                    if (std::equal(nums.begin() + start, nums.begin() + start + L, nums.begin() + i)) {
                        return i;
                    }
                }
            }
            seen[h].emplace_back(i);
        }
        return -1;
    }
};
428900