<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>

from collections import defaultdict
class Solution:
    def search(self, L: int, n: int, S: str) -> str:
        """
        Search a substring of a given length
        that occurs at least 2 times.
        @return start position if the substring exists and -1 otherwise.
        """
        seen_occurrences = defaultdict(int)
        max_seen = 1
        max_string = ""
        for start in range(0, n - L + 1):
            tmp = S[start:start + L]
            seen_occurrences[tmp] += 1
            times_seen = seen_occurrences[tmp]
            if times_seen > max_seen:
                max_seen = times_seen
                max_string = tmp
        return max_string
    
    def longestDupSubstring(self, s: str) -> str:
        n = len(s)
        
        # binary search, L = repeating string length
        left, right = 1, n
        longest_string = ""
        while left <= right:
            L = left + (right - left) // 2
            max_duplicate = self.search(L, n, s)
            if max_duplicate:
                left = L + 1
                longest_string = max_duplicate
            else:
                right = L - 1
               
        return longest_string
239100