<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:
    def longestDupSubstring(self, s: str) -> str:
        def search(nums, length, base, mod):
            hash = 0
            for index in range(length):
                hash = (base * hash + nums[index]) % mod
            hashes = defaultdict(set)
            hashes[hash].add(0)

            pow_base_length_mod = pow(base, length, mod)

            for start in range(1, len(s) - length + 1):
                hash = (base * hash - nums[start - 1] * pow_base_length_mod + nums[start - 1 + length]) % mod
                if hash in hashes:
                    if any(s[start : start + length] == s[index : index + length] for index in hashes[hash]):
                        return start
                hashes[hash].add(start)
            return -1

        candidate_longest_index = 0
        candidate_longest_length = float('inf')

        nums = [ord(char) - ord('a') for char in s]
        base = 26
        mod = 10 ** 9 + 7

        left, right = 0, len(s) - 1
        while left <= right:
            mid = left + (right - left) // 2
            candidate_index = search(nums, mid, base, mod)
            if candidate_index == -1:
                right = mid - 1
            else:
                left = mid + 1
                candidate_longest_index = candidate_index
                candidate_longest_length = mid
        return s[candidate_longest_index : candidate_longest_index + candidate_longest_length]
28000