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?
  1. A. bdde fxxbyyfbcd
  2. B. bcde fbcd
  3. C. bcde fxxbyyfbcd
  4. 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

Exams that ask this topic