I'm looking to explore different algorithms, both recursive and dynamic programming, that checks if one arrayA is a subsequence of arrayB. For example,
arrayA = [1, 2, 3]
arrayB = [5, 6, 1, 7, 2, 9, 3]
thus, arrayA is indeed a subsequence of arrayB.
I've tried a few different searches, but all I can seem to find is algorithms to compute the longest increasing subsequence.
And here's a python example:
Here is an example in Ruby:
Since you must match all elements of
arrayA
to some elements ofarrayB
, you never need to backtrack. In other words, if there are two candidates inarrayB
to match an element ofarrayA
, you can pick the earliest one, and never retract the choice.Therefore, you do not need DP, because a straightforward linear greedy strategy will work:
As dasblinkenlight has correctly said(and i could not have phrased it better than his answer!!) a greedy approach works absolutely fine. You could use the following pseudocode (with just a little more explanation but totally similar to what dasblinkenlight has written)which is similar to the merging of two sorted arrays.
Time Complexity is O(|A|+|B|) in the worst case, where |A| & |B| are the number of elements present in Arrays
A
andB
respectively. Thus you get a linear complexity.