Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.
Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".
Input: s = "banana"
Output: "ana"
Input: s = "abcd"
Output: ""
s consists of lowercase English letters.The brute force approach is to generate all possible substrings and check if more than one instance of a substring exists. Although this will work eventually, it's far from optimal. Given the nature of substrings, we can sort them and then check adjacent pairs for duplicates.
The general idea is to consider substrings of all possible lengths, starting from the longest. If we find a duplicate substring of a certain length, we record that as our longest duplicate substring.
The optimized approach uses binary search combined with a rolling hash technique to efficiently determine the longest duplicate substring.
left as 1 and right as n (length of string).This method narrows down to the longest possible duplicate substring by leveraging the logarithmic exploration of the binary search and the efficiency of rolling hash.
log n factor, and each call to check for duplicates using rolling hash is O(n).