Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of substrings of that length.

Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of substrings of that length.
def longest_dup(s):
    def find(L):
        seen = set()
        for i in range(len(s) - L + 1):
            t = s[i:i+L]
            if t in seen: return t
            seen.add(t)
        return None
    lo, hi, best = 1, len(s) - 1, ""
    while lo <= hi:
        mid = (lo + hi) // 2; t = find(mid)
        if t: best, lo = t, mid + 1
        else: hi = mid - 1
    return best
print(longest_dup("banana"), longest_dup("abcabcab"))
What is printed?
  1. A. an abc
  2. B. ana bcab
  3. C. ana abcab
  4. D. na abcab

Correct answer: C. ana abcab

If a length-L duplicate exists, so does every shorter one (take a prefix), so the predicate is monotone and binary search applies. 'ana' occurs at 1 and 3 (overlapping); in 'abcabcab', 'abcab' occurs at 0 and 3.

More Coding Interview Problems questions

Exams that ask this topic