<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:
        longest_duplicate_substring = ""
        min_len, max_len = 0, len(s) - 1
        while min_len <= max_len:  # While must include the case min len = max len.
            if min_len == 0 and max_len == 1:  # Special case.
                mid_len = 1

            else:
                mid_len = (min_len + max_len) // 2

            duplicate_substring = self._detect_duplicate_substring(s, mid_len)
            if duplicate_substring:  # Can try a longer length.
                longest_duplicate_substring = duplicate_substring
                min_len = mid_len + 1
                continue
            max_len = mid_len - 1  # Must try a shorter length.

        return longest_duplicate_substring

    @staticmethod
    def _detect_duplicate_substring(string: str, window_size: int, base: int = 31, mod: int = 2 ** 34 - 1):
        str_len = len(string)
        powers = [1] + [0] * str_len  # 1st power starts from 1.
        hash_values = set()

        for i in range(1, str_len + 1):  # Precompute powers of base, and modulo over mod.
            powers[i] += (powers[i - 1] * base) % mod

        window_hash = 0
        for i in range(window_size):  # Hash value of 1st window.
            window_hash *= base
            window_hash += ord(string[i])
            window_hash %= mod
        hash_values.add(window_hash)

        for i in range(1, str_len - window_size + 1):  # Hash values of the rest windows.
            # Remove contribution of window's 1st char.
            window_hash -= powers[window_size - 1] * ord(string[i - 1])
            window_hash %= mod

            window_hash *= base  # Shift window by one char and add new char to hash.
            window_hash += ord(string[i + window_size - 1])
            window_hash %= mod

            if window_hash in hash_values:  # Duplicate detected.
                return string[i: i + window_size]
            hash_values.add(window_hash)

        return None

22200