DSA Explorer
QuicksortMerge SortBubble SortInsertion SortSelection SortHeap SortCounting SortRadix SortBucket SortShell SortTim SortCocktail Shaker SortComb SortGnome SortPancake SortPatience SortCycle SortStrand SortWiggle Sort (Wave Sort)Bead Sort (Gravity Sort)Binary Insertion SortBitonic SortBogo Sort (Stupid Sort)Stooge SortOdd-Even Sort (Brick Sort)Pigeonhole SortIntro Sort (Introspective Sort)Tree Sort (BST Sort)Dutch National Flag (3-Way Partitioning)
Binary SearchLinear SearchJump SearchInterpolation SearchExponential SearchTernary SearchFibonacci SearchQuick Select (k-th Smallest)Median of Medians (Deterministic Select)Hill climbingSimulated AnnealingTabu SearchBinary Tree DFS SearchSentinel Linear SearchDouble Linear SearchTernary Search (Unimodal Function)Search in 2D Matrix
Binary Search Tree (BST)StackQueueHash Table (Hash Map)Heap (Priority Queue)Linked ListTrie (Prefix Tree)Binary TreeTrie (Prefix Tree)Floyd's Cycle Detection (Tortoise and Hare)Merge Two Sorted Linked ListsCheck if Linked List is PalindromeFind Middle of Linked ListBalanced Parentheses (Valid Parentheses)Next Greater ElementInfix to Postfix ConversionMin Stack (O(1) getMin)Largest Rectangle in HistogramDaily Temperatures (Monotonic Stack)Evaluate Reverse Polish NotationInfix Expression Evaluation (Two Stacks)Min Heap & Max HeapSliding Window MaximumTrapping Rain WaterRotate Matrix 90 DegreesSpiral Matrix TraversalSet Matrix ZeroesHash Table with ChainingOpen Addressing (Linear Probing)Double HashingCuckoo Hashing
Depth-First Search (DFS)Breadth-First Search (BFS)Dijkstra's AlgorithmFloyd-Warshall AlgorithmKruskal's AlgorithmPrim's AlgorithmTopological SortA* Pathfinding AlgorithmKahn's Algorithm (Topological Sort)Ford-Fulkerson Max FlowEulerian Path/CircuitBipartite Graph CheckBorůvka's Algorithm (MST)Bidirectional DijkstraPageRank AlgorithmBellman-Ford AlgorithmTarjan's Strongly Connected ComponentsArticulation Points (Cut Vertices)Find Bridges (Cut Edges)Articulation Points (Cut Vertices)Finding Bridges (Cut Edges)
0/1 Knapsack ProblemLongest Common Subsequence (LCS)Edit Distance (Levenshtein Distance)Longest Increasing Subsequence (LIS)Coin Change ProblemFibonacci Sequence (DP)Matrix Chain MultiplicationRod Cutting ProblemPalindrome Partitioning (Min Cuts)Subset Sum ProblemWord Break ProblemLongest Palindromic SubsequenceMaximal Square in MatrixInterleaving StringEgg Drop ProblemUnique Paths in GridCoin Change II (Count Ways)Decode WaysWildcard Pattern MatchingRegular Expression MatchingDistinct SubsequencesMaximum Product SubarrayHouse RobberClimbing StairsPartition Equal Subset SumKadane's Algorithm (Maximum Subarray)
A* Search AlgorithmConvex Hull (Graham Scan)Line Segment IntersectionCaesar CipherVigenère CipherRSA EncryptionHuffman CompressionRun-Length Encoding (RLE)Lempel-Ziv-Welch (LZW)Canny Edge DetectionGaussian Blur FilterSobel Edge FilterHarris Corner DetectionHistogram EqualizationMedian FilterLaplacian FilterMorphological ErosionMorphological DilationImage Thresholding (Otsu's Method)Conway's Game of LifeLangton's AntRule 30 Cellular AutomatonFast Fourier Transform (FFT)Butterworth FilterSpectrogram (STFT)
Knuth-Morris-Pratt (KMP) AlgorithmRabin-Karp AlgorithmBoyer-Moore AlgorithmAho-Corasick AlgorithmManacher's AlgorithmSuffix ArraySuffix Tree (Ukkonen's Algorithm)Trie for String MatchingEdit Distance for StringsLCS for String MatchingHamming DistanceJaro-Winkler DistanceDamerau-Levenshtein DistanceBitap Algorithm (Shift-Or, Baeza-Yates-Gonnet)Rolling Hash (Rabin-Karp Hash)Manacher's AlgorithmZ AlgorithmLevenshtein Distance

Longest Common Subsequence (LCS)

Dynamic Programming
O(mn) time, O(mn) space
Intermediate

Finds the longest subsequence common to two sequences. A subsequence is a sequence that appears in the same relative order but not necessarily contiguously. This is fundamental in diff utilities, DNA sequence analysis, and version control systems like Git.

Prerequisites:
Dynamic Programming
String manipulation
2D Arrays

Visualization

Interactive visualization for Longest Common Subsequence (LCS)

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

Language:
1function lcs(str1: string, str2: string): number {
2  const m = str1.length;
3  const n = str2.length;
4  const dp: number[][] = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));
5  
6  for (let i = 1; i <= m; i++) {
7    for (let j = 1; j <= n; j++) {
8      if (str1[i - 1] === str2[j - 1]) {
9        dp[i][j] = 1 + dp[i - 1][j - 1];
10      } else {
11        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
12      }
13    }
14  }
15  
16  return dp[m][n];
17}
18
19// Get actual LCS string
20function getLCS(str1: string, str2: string): string {
21  const m = str1.length;
22  const n = str2.length;
23  const dp: number[][] = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));
24  
25  for (let i = 1; i <= m; i++) {
26    for (let j = 1; j <= n; j++) {
27      if (str1[i - 1] === str2[j - 1]) {
28        dp[i][j] = 1 + dp[i - 1][j - 1];
29      } else {
30        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
31      }
32    }
33  }
34  
35  // Backtrack to find actual LCS
36  let result = '';
37  let i = m, j = n;
38  while (i > 0 && j > 0) {
39    if (str1[i - 1] === str2[j - 1]) {
40      result = str1[i - 1] + result;
41      i--;
42      j--;
43    } else if (dp[i - 1][j] > dp[i][j - 1]) {
44      i--;
45    } else {
46      j--;
47    }
48  }
49  
50  return result;
51}

Deep Dive

Theoretical Foundation

LCS uses a 2D DP table where dp[i][j] represents the length of the LCS of the first i characters of string1 and first j characters of string2. The solution builds up from smaller subproblems, avoiding exponential brute force complexity.

Complexity

Time

Best

O(mn)

Average

O(mn)

Worst

O(mn)

Space

Required

O(mn)

Applications

Industry Use

1

DNA sequence comparison in bioinformatics

2

File diff utilities (diff, git diff)

3

Plagiarism detection

4

Data compression algorithms

5

Speech recognition systems

6

Longest common substring in databases

Use Cases

DNA sequence analysis
File diff
Plagiarism detection

Related Algorithms

0/1 Knapsack Problem

A classic optimization problem where you must select items with given weights and values to maximize total value without exceeding the knapsack's capacity. Each item can be taken only once (0 or 1). This is a fundamental problem in combinatorial optimization, resource allocation, and decision-making scenarios.

Dynamic Programming

Edit Distance (Levenshtein Distance)

Edit Distance, also known as Levenshtein Distance, computes the minimum number of single-character edits (insertions, deletions, or substitutions) required to transform one string into another. Named after Soviet mathematician Vladimir Levenshtein who introduced it in 1965, this fundamental algorithm has applications in spell checking, DNA sequence analysis, natural language processing, and plagiarism detection.

Dynamic Programming

Longest Increasing Subsequence (LIS)

Longest Increasing Subsequence (LIS) finds the length of the longest subsequence in an array where all elements are in strictly increasing order. Unlike a subarray, a subsequence doesn't need to be contiguous - elements can be selected from anywhere as long as their order is preserved. This classic DP problem has two solutions: O(n²) dynamic programming and O(n log n) binary search with patience sorting. Applications include stock price analysis, scheduling, Box Stacking Problem, and Building Bridges Problem.

Dynamic Programming

Coin Change Problem

The Coin Change Problem finds the minimum number of coins needed to make a given amount using unlimited supplies of given coin denominations. It's a classic example of both dynamic programming and greedy algorithms, with two main variants: finding the minimum number of coins (optimization) and counting the number of ways to make change (counting). This problem has direct applications in currency systems, vending machines, and resource optimization.

Dynamic Programming
DSA Explorer

Master Data Structures and Algorithms through interactive visualizations and detailed explanations. Our platform helps you understand complex concepts with clear examples and real-world applications.

Quick Links

  • About DSA Explorer
  • All Algorithms
  • Data Structures
  • Contact Support

Legal

  • Privacy Policy
  • Terms of Service
  • Cookie Policy
  • Code of Conduct

Stay Updated

Subscribe to our newsletter for the latest algorithm explanations, coding challenges, and platform updates.

We respect your privacy. Unsubscribe at any time.

© 2026 Momin Studio. All rights reserved.

SitemapAccessibility
v1.0.0