LCS for String Matching
Find longest subsequence present in both strings. Classic DP problem optimized for string comparison.
Visualization
Interactive visualization for LCS for String Matching
Longest Common Subsequence (LCS)
• Time: O(m × n) where m, n are string lengths
• Space: O(m × n) for DP table
• Used in diff tools, DNA sequence alignment, version control
Interactive visualization with step-by-step execution
Implementation
1function lcs(s1: string, s2: string): string {
2 const m = s1.length, n = s2.length;
3 const dp = Array(m+1).fill(0).map(() => Array(n+1).fill(0));
4
5 for (let i = 1; i <= m; i++) {
6 for (let j = 1; j <= n; j++) {
7 if (s1[i-1] === s2[j-1]) {
8 dp[i][j] = dp[i-1][j-1] + 1;
9 } else {
10 dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
11 }
12 }
13 }
14
15 // Backtrack
16 let result = '';
17 let i = m, j = n;
18 while (i > 0 && j > 0) {
19 if (s1[i-1] === s2[j-1]) {
20 result = s1[i-1] + result;
21 i--; j--;
22 } else if (dp[i-1][j] > dp[i][j-1]) {
23 i--;
24 } else {
25 j--;
26 }
27 }
28 return result;
29}Deep Dive
Theoretical Foundation
dp[i][j] = LCS length of s1[0..i] and s2[0..j]. If match: 1+dp[i-1][j-1]. Else: max(dp[i-1][j], dp[i][j-1]).
Complexity
Time
O(m×n)
O(m×n)
O(m×n)
Space
O(m×n)
Applications
Use Cases
Related Algorithms
Knuth-Morris-Pratt (KMP) Algorithm
An efficient string pattern matching algorithm that searches for occurrences of a 'word' within a 'text' by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin. Developed by Donald Knuth, Vaughan Pratt, and James H. Morris in 1977, it's one of the most important string algorithms with O(n+m) time complexity.
Rabin-Karp Algorithm
A string-searching algorithm that uses hashing to find pattern(s) in a text. Developed by Michael O. Rabin and Richard M. Karp in 1987, it's particularly useful for multiple pattern search and plagiarism detection. Uses rolling hash for efficiency.
Boyer-Moore Algorithm
One of the most efficient string searching algorithms in practice, using two heuristics: bad character rule and good suffix rule. Developed by Robert S. Boyer and J Strother Moore in 1977, it's the standard benchmark for practical string search, often outperforming other algorithms by skipping sections of text.
Aho-Corasick Algorithm
A string-searching algorithm for locating elements of a finite set of strings (dictionary) within an input text. Invented by Alfred V. Aho and Margaret J. Corasick in 1975, it's a kind of dictionary-matching algorithm that simultaneously searches for all patterns in linear time, making it extremely efficient for multiple pattern matching.