<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_las_vegas(s)
        # return self.longest_duplicate_rabin_karp_monte_carlo(s)
        # return self.longest_duplicate_rabin_karp_double_hash(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_las_vegas(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
        # for q = 1e7 + 7, there are hash collisions, because M.N^2 <= Q is false
        # so there are a few ways to fix this
        # 1st method is to use las vegas version of rabin karp, where we check the substring before returning
        # we do this, by making seen a dict and storing indices for hash, then checking the substring when we find a hash in seen

        # time: O((m + n)logn) rabin karp rolling hash takes O(m + n) where m is length of pattern being searched and n = total string length
        # since m can be at most n, and sometimes << n
        # For worst case when there are collisions, since we need to check the string, the time becomes O(mn) instead of O(m + n) which is brute force
        # so it kinda depends how many collisions we have
        # we get time: O(nlogn) best case and O(mnlogn) worst case
        # space: O(n) for seen

        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 = collections.defaultdict(int)
            
            # 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[h] = 0  # add initial hash to seen

            # 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

                # 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). 
                # step 2: Then take mod q for that entire term with hash + q.
                # step 3: 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 seen: 
                    prev_index = seen[h]
                    if s[i:i + length] == s[prev_index:prev_index + length]: # compare both strings, las vegas version
                        return i  # repeating
                else:
                    seen[h] = i
            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]

    def longest_duplicate_rabin_karp_monte_carlo(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
        # for q = 1e7 + 7, there are hash collisions, because M.N^2 <= Q is false
        # so there are a few ways to fix this
        # 1st method is to use las vegas version of rabin karp, where we check the substring before returning
        # we do this, by making seen a dict and storing indices for hash, then checking the substring when we find a hash in seen
        # this method uses the monte carlo version, without checking the substring, but we make sure to use a larger prime
        # 2^63 - 1 is a prime which is 10^18 so it avoids hash collisions

        # time: O((m + n)logn) rabin karp rolling hash takes O(m + n) where m is length of pattern being searched and n = total string length
        # since m can be at most n, and sometimes << n
        # we get time: O(nlogn)
        # space: O(n) for seen

        n = len(s)
        q = 2 ** 63 - 1  # 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 = collections.defaultdict(int)

            # 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[h] = 0  # add initial hash to seen

            # 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

                # 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).
                # step 2: Then take mod q for that entire term with hash + q.
                # step 3: 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 seen:
                    return i
                else:
                    seen[h] = i
            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]

    def longest_duplicate_rabin_karp_double_hash(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
        # for q = 1e7 + 7, there are hash collisions, because M.N^2 <= Q is false
        # so there are a few ways to fix this
        # this method uses double hashing to remove hash collisions
        # basically, calculate 2 different hashes using 2 q's and even 2 radix R. We can take R to be anything greater than what we initially took
        # using same radix base 26 here btw

        # time: O((m + n)logn) rabin karp rolling hash takes O(m + n) where m is length of pattern being searched and n = total string length
        # since m can be at most n, and sometimes << n
        # we get time: O(nlogn)
        # space: O(n) for seen


        n = len(s)
        q1 = 1e9 + 7
        q2 = 1e9 + 33

        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 = collections.defaultdict(int)

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

            # find initial hash
            h1, h2 = 0, 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
                h1 = (h1 * 26 + ord(s[j])) % q1
                h2 = (h2 * 26 + ord(s[j])) % q2
                j += 1

            seen[(h1, h2)] = 0  # add initial hash to seen

            # 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

                # 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).
                # step 2: Then take mod q for that entire term with hash + q.
                # step 3: Then we multiply by R, add new digit and take final mod q

                h1 = (h1 + q1 - ((ord(s[i - 1]) * rm1) % q1)) % q1
                h1 = ((h1 * 26) + ord(s[i + length - 1])) % q1

                h2 = (h2 + q2 - ((ord(s[i - 1]) * rm2) % q2)) % q2
                h2 = ((h2 * 26) + ord(s[i + length - 1])) % q2

                if (h1, h2) in seen: # confident there wont be any collisions
                    return i
                else:
                    seen[(h1, h2)] = i
            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]
21900