Longest Common Subsequence (LCS) - Dynamic Programming
Nikola AndrićNikola Andrić
Problem:
Problem:
Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”.
This problem can easily solved recursively. However, that is not good enough. There is a lot overlapping when it comes to long sequences and the runtime is O(n2) in the worst case when the sequences have no common characters.
In the following image of a partial tree, we can see taht there are places where coputation was repeated.
We can solve this using a bottom-up dynamic programming approach, which avoids redundant computation, as follows:
Once this code has been executed, you will be able to see the table created and follow the printing part pf the function and recognize the pattern used to print the LCS.
The following image was taken from Wiki and represents an example how printing path would look like: