<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(length):
            base = 257  # Choose a base larger than ASCII characters to minimize collisions
            mod = 2**61 - 1  # A large prime modulus
            hashes = defaultdict(int)
            cur_hash = 0
            base_l = 1
            
            for i in range(length):
                base_l = (base_l * base) % mod
                cur_hash = (cur_hash * base + ord(s[i])) % mod
            
            hashes[cur_hash] = 0
            
            for i in range(length, len(s)):
                cur_hash = (cur_hash * base + ord(s[i]) - ord(s[i - length]) * base_l) % mod
                if cur_hash in hashes:
                    if s[hashes[cur_hash]:hashes[cur_hash] + length] == s[i - length + 1:i + 1]:
                        res[length] = s[i - length + 1:i + 1]
                        return True
                hashes[cur_hash] = i - length + 1
            
            return False

        n = len(s)
        left, right = 1, n
        best_len = 0
        res = {}

        while left <= right:
            mid = (left + right) // 2
            if search(mid):
                best_len = mid
                left = mid + 1
            else:
                right = mid - 1

        return res.get(best_len, "")
21000