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?- A. bcde abc ''
- B. bdde abc 'cb'
- C. bcde xaxbxc ''
- 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
- Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] C] R – every row is…
- Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again. python…
- Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches…
- Problem: Single machine, jobs (name, duration, due time); lateness = finish − due. Minimise the MAXIMUM lateness. Compare…
- Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a…
- Problem: Find all critical links (bridges) and critical routers (articulation points) with one DFS using discovery times and low-links…