Dynamic
Programming
Team
Subaina Norab 22-NTU-CS-1374
Shaham Hijab 22-NTU-CS-1373
Hadia Alvi 22-NTU-CS-1343
Summaiya 22-NTU-CS-1376
01. Characterize the structure of
optimal solution
Dynamic
Programming 02. Recursively define the value
of optimal solution
The idea is to simply store the results of
subproblems so that we do not have to
re-compute them when needed later Compute the value of
03. optimal solution in bottom
up manner(Optimal Value
and Sequence)
Longest
common
subsequence
It involves finding the longest sequence
of characters that appear in the same
order in two given strings, but not
necessarily consecutively.
Process
TABLE FILL Backtrack
Fill the table Start from (bottom-right corner of table and
Create a table(2D araray)
• if characters match: move towards the top-left:
and fill it with 0
Add 1 to the LCS length from the • If characters match:
previous diagonal cell ⚬ Add the character to the result lcs
string (prepend it).
• if characters don't match: ⚬ Move diagonally up-left in the DP
Take the maximum value from table.
the left) or above cell
Table
Code
const m = str1.length;
const n = str2.length; while (i > 0 && j > 0) {
// if character match
// Create table filled with zeros
// (i-1,j) -> value above the current cell; (i,j-1)->value to
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
the left of the current cell
// Fill array if (str1[i - 1] === str2[j - 1]) {
for (let i = 1; i <= m; i++) { lcs = str1[i - 1] + lcs;
for (let j = 1; j <= n; j++) { i--;
// checking if characters match j--;
if (str1[i - 1] === str2[j - 1]) {
} else if (dp[i - 1][j] > dp[i][j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
// above
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); i--;
} } else {
} // left
} j--;
}
// extract
}
let i = m, j = n;
let lcs = ''; return lcs;
Longest
Common
Substring
The longest consecutive sequence of characters. that
appears in both strings.
Construct Table Fill Table
Construct Table and fill with
0s IF characters match add 1
else fill with 0
Extract Characters
After filling , take max
length and extract
characters
Code
const m = str1.length;
const n = str2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
let maxLength = 0;
let endIndex = 0;
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (str1[i - 1] === str2[j - 1]) {
// if equal add 1
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > maxLength) {
maxLength = dp[i][j];
endIndex = i;
}
} else {
dp[i][j] = 0;
}
}
}
// extract characters
return str1.substring(endIndex - maxLength, endIndex);
z a b c y z
: [0, 0, 0, 0, 0, 0, 0],
a:[0, 0, 1, 0, 0, 0, 0],
b:[0, 0, 0, 2, 0, 0, 0],
c:[0, 0, 0, 0, 3, 0, 0],
d:[0, 0, 0, 0, 0, 0, 0],
e:[0, 0, 0, 0, 0, 0, 0],
f:[0, 0, 0, 0, 0, 0, 0]
Thank you