Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then backward to tighten the start.
Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then backward to tighten the start.
def mws(S, T):
best, i = "", 0
while i < len(S):
j = 0
while i < len(S):
if S[i] == T[j]:
j += 1
if j == len(T): break
i += 1
if i == len(S): break
end = i; j = len(T) - 1
while j >= 0:
if S[i] == T[j]: j -= 1
i -= 1
i += 1
if not best or end - i + 1 < len(best): best = S[i:end + 1]
i += 1
return best
print(mws("abcdebdde", "bde"), mws("fxxbyyfbcd", "fbd"))What is printed?- A. bdde fxxbyyfbcd
- B. bcde fbcd
- C. bcde fxxbyyfbcd
- D. bdde fbcd
Correct answer: B. bcde fbcd
For 'bde' the forward scan ends at the first e (index 4); scanning back finds b at 1, giving 'bcde' (length 4); later 'bdde' also has length 4 but is not shorter, so the leftmost stays. For 'fbd' the window 'fbcd' (length 4) beats 'fxxbyyfbcd'.
More Coding Interview Problems questions
- Problem: Find the longest substring that occurs at least twice (occurrences may overlap): binary search on the length with a set of…
- 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…