<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:
        # return self.longest_duplicate_binary_search(s)
        return self.longest_duplicate_rabin_karp(s)

    def longest_duplicate_binary_search(self, s):
        # check binary search solution for L1062, this is same as that
        # time: O(n^2logn) helper is a linear loop and finding substr makes in n^2. Binary search is logn
        # time for helper is actually (n - L)L where L = length and loop runs n - L times. For finding substr, the length is always L. So O((n-L).L)
        # for small L, this is O(n), and for L ~ n/2, we get O(n^2)
        # space: O(Ln) where L = substr length

        n = len(s)

        def helper(length):

            seen = set()
            # if we need to find substr of length x, how far can we look until end
            # n - length. So for abcdef, if we want length = 2. We can go upto e which is at index 4. n = 6. n - length = 6 - 2 = 4.
            # So we do end up at index 4, but for python range, we do +1
            
            for i in range(n - length + 1):

                substr = s[i:i + length]
                # a small improvement on space complexity, hash the substr and store it. This removes the L factor since hash is constant space
                # substr = hash(s[i:i + length])

                if substr in seen:  # non inclusive, so this works out nice
                    return i  # i is the index of start of window substring. SO we return that index
                seen.add(substr)
            return -1 # -1 means not found

        lo, hi = 0, n - 1  # max range of longest length is n - 1. Because length n cannot repeat, it will be the entire length thats why
        start = 0
        while lo < hi:
            mid = lo + (hi - lo + 1) // 2  # since lo ends up at mid, we need + 1 for right shifted mid
            match_index = helper(mid)
            if match_index >= 0:  # if this length is repeating, we look higher to find longest length
                lo = mid
                start = match_index # if we have a match index, we store it
            else:
                hi = mid - 1

        # this will return "" when not found. Because our binary search keeps shrinking to find lower length and ends up at 0, then s[0:0] = ""
        return s[start:start + lo] # lo will be the length of substring we found to be valid, and we know it starts from index start

    def longest_duplicate_rabin_karp(self, s):
        # similar to L1062, but here we modify the rolling hash function to be more resilient with hash collisions
        # since the constraint is very large here

        n = len(s)
        q = 1e7 + 7 # large prime

        def helper(length):
            # since we have alphabets, we can take R = 26.
            # remember that hash = a0 * 26^(length-1) + a1 * 26(length-2).... + ak * 26^0. Where k = length since thats the length of pattern we are trying to match
            # and to get a new hash, we do ( h - xi(r^(m - 1) )R + x0. Where xi is leading digit removed, and x0 is new digit

            seen = set()

            # precompute r^(m-1) % q where r = 26, m = length
            rm = 1
            m = 1
            while m <= length - 1: # do from length - 1 times
                rm = (rm * 26) % q
                m += 1

            # find initial hash
            h = 0
            j = 0
            while j <= length - 1:  # repeat m - 1 times where m = length
                # first time, we get h = s[j]. Then s[j] * 26 + s[j + 1]. Eventually the leading digit has 26^(length - 1) and last one as no factor
                h = ( h * 26 + ord(s[j]) ) % q
                j += 1

            seen.add(h)  # add to seen
            hash_map = collections.defaultdict(int)

            # now move the hash forward and check if we have a duplicate hash anytime
            # if we need to find substr of length x, how far can we look until end
            # n - length. So for abcdef, if we want length = 2. We can go upto e which is at index 4. n = 6. n - length = 6 - 2 = 4.
            # So we do end up at index 4, but for python range, we do +1
            for i in range(1, n - length + 1):  # start from 1 cuz we look at hash from 0

                # leading digit will be 1 behind
                # and new digit is at + length - 1 cuz of indexes
                # h = (h - ord(s[i - 1]) * 26 ** (length - 1)) * 26 + ord(s[i + length - 1])
                # h = (h + q - ((ord(s[i - 1]) * rm) % q) * 26) + ord(s[i + length - 1])

                # hash = (hash + q - xi * r^(m-1) )R + x0
                # ( X - xi * R^(M-1) )R + x0
                # step 1: we take mod q after xi * r^(m-1). Then take mod q for that entire term with hash + q.
                # Then we multiply by R, add new digit and take final mod q

                h = ( h + q - ( (ord(s[i - 1]) * rm) % q ) ) % q
                h = ( (h * 26) + ord(s[i + length - 1]) ) % q

                if h in hash_map:
                    # print("found h")
                    # print("current hash = ", h, "and current string = ", s[i:i + length])
                    # print("previous hash = ", h, "and previous string = ", hash_map[h])
                    pass
                else:
                    hash_map[h] = s[i:i + length]

                if h in seen:  # non inclusive, so this works out nice
                    if s[i:i + length] == hash_map[h]:
                        return i  # repeating
                seen.add(h)
            return -1

        lo, hi = 0, n - 1  # max range of longest length is n - 1. Because length n cannot repeat, it will be the entire length thats why
        start = 0
        while lo < hi:
            mid = lo + (hi - lo + 1) // 2  # since lo ends up at mid, we need + 1 for right shifted mid
            match_index = helper(mid)
            if match_index >= 0:  # if this length is repeating, we look higher to find longest length
                lo = mid
                start = match_index  # if we have a match index, we store it
            else:
                hi = mid - 1
        return s[start:start + lo]
242100