<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:
        # smallest possible substring: single charafcter --> counter
        # 2-character substrings: 
        # binary search on possible length

        n = len(s) 
        def isDupLen(l:int) -> bool:
            # check is there exists length-l substring that duplicates
            # counter
            # rolling hash
            record = set()
            for i in range(n-l+1):
                subStr = s[i:i+l] # 0 l-1 -> l
                # print("i:{}, i+l-1:{}, subStr:{}".format(i, i+l-1, subStr))
                if subStr in record: return True, subStr
                record.add(subStr)

            return False, ""

        left, right = 0, n-1
        while left < right -1:
            mid = (left+right)//2
            flag, _ = isDupLen(mid)
            # print("left:{}, right:{}, mid:{}, flag:{}".format(left,right, mid, flag))
            if flag: left = mid
            else: right = mid-1

        flag, dupStr = isDupLen(right)
        if flag: return dupStr

        flag, dupStr = isDupLen(left)
        if flag: return dupStr
        return ""
        
240200