Step 1: Initialize a 2D table with dimensions (length of String1 + 1) x (length of String2 + 1) filled with zeros
[[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
Why: We need this table to store lengths of LCS for substrings to build up the solution
Step 2: Compare characters 'A' (String1[0]) and 'A' (String2[0]), they match, set table[1][1] = 1 + table[0][0] = 1
[[0,0,0,0,0,0,0],
[0,1,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
Why: Matching characters increase LCS length by 1 from previous substrings
Step 3: Compare 'B' (String1[1]) and 'E' (String2[1]), no match, set table[2][2] = max(table[1][2], table[2][1]) = 1
[[0,0,0,0,0,0,0],
[0,1,0,0,0,0,0],
[0,1,1,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
Why: No match means LCS length is max of ignoring one character from either string
Step 4: Compare 'D' (String1[3]) and 'D' (String2[2]), match, set table[4][3] = 1 + table[3][2] = 2
[[0,0,0,0,0,0,0],
[0,1,0,0,0,0,0],
[0,1,1,0,0,0,0],
[0,1,1,1,0,0,0],
[0,1,1,2,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
Why: Matching characters extend the LCS by 1 from previous substrings
Step 5: Compare 'H' (String1[5]) and 'H' (String2[4]), match, set table[6][5] = 1 + table[5][4] = 3
[[0,0,0,0,0,0,0],
[0,1,0,0,0,0,0],
[0,1,1,0,0,0,0],
[0,1,1,1,0,0,0],
[0,1,1,2,2,2,2],
[0,1,1,2,2,2,2],
[0,1,1,2,2,3,3]]
Why: Last matching characters increase LCS length to 3
Step 6: Trace back from table[6][6] to find LCS characters: H, D, A
LCS = "ADH"
Why: Backtracking finds the actual longest common subsequence
Result: Final LCS length table last cell: 3
Longest Common Subsequence: ADH