Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find the shortest substring of s that contains t as a SUBSEQUENCE (leftmost if several). Two pointers: scan forward to complete t, then scan backward from that end to tighten the start.

Problem: Find the shortest substring of s that contains t as a SUBSEQUENCE (leftmost if several). Two pointers: scan forward to complete t, then scan backward from that end to tighten the start.
def min_window_subseq(s, t):
    best = (10**9, -1)
    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 end - i + 1 < best[0]: best = (end - i + 1, i)
        i += 1
    return "" if best[1] < 0 else s[best[1]:best[1] + best[0]]
print(min_window_subseq("abcdebdde", "bde"), min_window_subseq("xaxbxcabc", "abc"), repr(min_window_subseq("abc", "cb")))
What is printed?
  1. A. bcde abc ''
  2. B. bdde abc 'cb'
  3. C. bcde xaxbxc ''
  4. D. deb abc ''

Correct answer: A. bcde abc ''

The forward pass finds the earliest end where t is a subsequence; the backward pass from that end greedily matches t from its last letter, giving the latest possible start for that end – the shortest window ending there. Then the search restarts just after that start. abcdebdde: candidate windows bcde (4) and bdde (4); the first one is kept → 'bcde'. xaxbxcabc: the last three letters 'abc' (3) beat 'axbxc'. 'cb' cannot appear in order inside 'abc' → ''. Worst case O(|s|·|t|).

More Coding Interview Problems questions

Exams that ask this topic