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

'''
Rabin karp binary search
'''

b1 = 757
b2 = 313
mod = int(1e9+7)

class Solution:
    def longestDupSubstring(self, s: str) -> str:
        n=len(s)
        si=[ord(ch) - ord('a') for ch in s]
        powb1 = [0] * n
        powb2 = [0] * n
        powb1[0] = 1
        powb2[0]=1
        for i in range(1, n):
            powb1[i] = (powb1[i-1] * b1) % mod
            powb2[i] = (powb2[i-1] * b2) % mod

        # print(s)
        # print(si)
        # print(powb1)
        def check(k):
            # Check for duplicate substraings of len k
            hs = set()
            # get first hash
            h1 = 0
            h2 = 0
            for i in range(k):
                h1 = h1 * b1 % mod
                h1 = (h1 + si[i]) % mod
                h2 = h2 * b2 % mod
                h2 = (h2 + si[i]) % mod
            hs.add((h1,h2))
            for i in range(k, n):
                rmi=i-k
                rmx=si[rmi]
                sub1 = rmx * powb1[k-1] % mod
                sub2 = rmx * powb2[k-1] % mod
                h1 = (h1 - sub1 + mod) % mod
                h1 = (h1 * b1 + si[i]) % mod
                h2 = (h2 - sub2 + mod ) % mod
                h2 = (h2 * b2 + si[i]) % mod
                if (h1,h2) in hs:
                    return i-k+1
                hs.add((h1,h2))
            return None
            
        lo=1
        hi=n-1
        ans_idx = None
        ans_len = None
        while lo<=hi:
            mid = (lo+hi)//2
            idx = check(mid)
            # print(mid, idx)
            if idx is None:
                # not found, go left
                hi = mid-1
            else:
                ans_idx = idx
                ans_len = mid
                lo=mid+1

        if ans_idx is None:
            return ""
        return s[ans_idx:ans_idx+ans_len]


25900