Step 1: Initialize a 2D array dp with dimensions (7 x 7) filled with zeros (lengths of strings + 1).
dp matrix 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 a table to store lengths of LCS for substrings to build up the solution.
Step 2: Compare characters at positions i=1 (A) and j=1 (A), they match, so dp[1][1] = dp[0][0] + 1 = 1.
dp[1][1] = 1
Partial dp:
[0,0,0,0,0,0,0]
[0,1,0,0,0,0,0]
...
Why: Matching characters add 1 to the LCS length from previous substrings.
Step 3: Compare i=2 (B) and j=2 (E), no match, so dp[2][2] = max(dp[1][2], dp[2][1]) = max(0,1) = 1.
dp[2][2] = 1
Partial dp:
[0,0,0,0,0,0,0]
[0,1,0,0,0,0,0]
[0,1,1,0,0,0,0]
...
Why: No match means we take the best LCS length from previous substrings.
Step 4: Compare i=4 (D) and j=3 (D), match found, dp[4][3] = dp[3][2] + 1 = 2.
dp[4][3] = 2
Partial dp:
...
[0,1,1,2,...]
...
Why: Matching characters increase LCS length by 1 from previous substrings.
Step 5: Fill the rest of dp table by comparing all characters and taking max or adding 1 on match.
Final dp matrix:
[0,0,0,0,0,0,0]
[0,1,1,1,1,1,1]
[0,1,1,1,1,1,1]
[0,1,1,1,1,1,1]
[0,1,1,2,2,2,2]
[0,1,1,2,2,2,2]
[0,1,1,2,2,3,3]
Why: Complete dp table gives lengths of LCS for all substring pairs.
Step 6: Trace back from dp[6][6] to find the LCS string by moving diagonally on matches or up/left on max values.
LCS found: A D H
Why: Backtracking reconstructs the actual longest common subsequence.
Result: Final LCS length = 3
LCS string = "ADH"