I saw this interview question at https://www.youtube.com/watch?v=10WnvBk9sZc and wanted to see if I was able to solve it. The code is not pretty but it does work. No maps are needed. No state tracking is needed, except for storing the current largest subsequence. Once a larger one is found, the previous one is no longer needed.
The basic concept is to start with the smallest string first as the string which is the largest cannot possibly be completely found in the smaller string. i.e. ABCDE could not ever completely match ABCD. But ABCD can sub match ABCDE.
If this calculation was to be done by a human, we would start at the first letter in the string and then start searching the
second string until we found a match. Once we found a match, we would go back to the first string and grab the next letter and then
continue searching the second string again; skipping any non-matching letters along the way. We would need to make sure to pick up
where we left off in the second string as to not get the matches out of order. This is where str2Index
comes into play.
Because the first letter of the first string may not even be in the second string, we will need to eventually skip it. The same applies to the n-th letter of the first string. This is why there are two loops. The first loop tells the second loop where to start when picking the letter to check between the strings.
For example: "AGGTAB", "GXTXAYB" => "GTAB"
Start with A and begin searching "GXTXAYB". "A" is not found until the fourth index is reached. And then another match does not occur until "B" is matched with the 6th index of the second string. This results in a match of "AB" which happens to be the largest match so far.
The next step is to then start at the 1st index of "AGGTAB", which is "G". We've already processed starting with "A" and that resulted in "AB". Starting with "G" results in a match at index 0 of the second string. The next "G" does not match anything. "T" matches the 2nd index. "A" matches the 4th index. and finally "B" matches the 6th index. match equals "GTAB".
I did the work using jsfiddle.net as it's really easy to execute javascript and see the results.