Skip to interview prep
Apexed

52. Show the DP table for the longest common subsequence.

MediumDynamic programming

Technical

Type or dictate your answer. Your draft is saved on this device.

Show model answer

dp[i][j] is the LCS length of the first i characters of a and the first j characters of b. If a[i−1] equals b[j−1], dp[i][j] = dp[i−1][j−1] + 1; otherwise it is the larger of dp[i−1][j] and dp[i][j−1]. The program prints the table and reconstructs one LCS by walking back from the corner.

Example program

Show the DP table for the longest common subsequence. — Data structures & algorithms interview question — Apexed