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?- A. an abc
- B. ana bcab
- C. ana abcab
- 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
- Problem: Count how many words are subsequences of s, by bucketing words by the next character they are waiting for. python from…
- Problem: Roads are one-way (a → b). Reorient the fewest roads so every city can reach city 0 (the roads form a tree). python def…
- Problem: A grid has exactly two islands (1s). Find the minimum number of 0s to flip to connect them (BFS outward from the first island)…
- Problem: Return the city that can reach the FEWEST other cities within a distance threshold (largest index on ties), using Floyd–Warshall…
- Problem: Count all paths from node 0 to node n − 1 in a DAG (memoised DFS). python from functools import lrucache g = {0: [1, 2, 3], 1…
- Problem: Rebuild a binary tree from its inorder and postorder traversals (distinct values) and print its preorder. python def prefrom(ino…