-1

Given a string S of length N, a string A of length M, a string B of length O such that N >= M + O. Check if the string S can be split into two subsequences X and Y such that A = X and B = Y.

Example: S = "abCDEfgH", A = "abfg", B = "CDEH" => answer is Yes S = "abcDEG", A = "acdG", B = "ED"

I found that this can be solved by dynamic programming but having a tough time finding a recursion. Can someone tell me the recursion and also an intuitive explanation of it? Thanks in advance!

harun_a
  • 135
  • 2

1 Answers1

0

We'll use indices (i, j, k) to keep track of how much we've seen of each string (S, A, B).

  • If we've seen all of S, then return YES if we've seen all of A and all of B,
  • If S[i] == A[j], then recurse on (i+1, j+1, k),
  • If S[i] == B[k], then recurse on (i+1, j, k+1).

Implement this as a memoized recursive function. This has time complexity O(S * A * B).

mrk
  • 3,748
  • 23
  • 35