The Longest Common Subsequence (LCS) algorithm finds the longest sequence of tokens—characters, words, or lines—that appear in identical order in two input sequences, though not necessarily contiguously. By identifying this maximal shared structure, LCS implicitly defines the minimal set of insertions and deletions required to transform one document into the other, making it the mathematical core of the diff utility and modern document comparison engines.
Glossary
Longest Common Subsequence (LCS)

What is Longest Common Subsequence (LCS)?
The Longest Common Subsequence (LCS) is a classic dynamic programming algorithm that identifies the longest sequence of characters or lines appearing in the same relative order within two documents, forming the computational basis for minimal edit-distance calculations.
In legal document analysis, LCS operates at the line or clause level to compute a minimal edit script between contract versions. The algorithm constructs a dynamic programming table with O(m*n) time and space complexity, where m and n are the lengths of the two sequences. The resulting diff highlights only the necessary changes, enabling precise redline analysis and ensuring that no spurious modifications are introduced during the comparison of complex transactional documents.
Core Properties of LCS
The Longest Common Subsequence algorithm is the mathematical backbone of modern diff engines. Understanding its core properties is essential for optimizing document comparison and redline analysis in legal AI systems.
Optimal Substructure
LCS exhibits optimal substructure, meaning the optimal solution to the full problem can be constructed efficiently from optimal solutions to its subproblems. If the last characters of two sequences match, that character is part of the LCS, and the problem reduces to finding the LCS of the remaining prefixes. If they differ, the LCS is the longer of two options: skipping the last character of the first sequence or skipping the last character of the second. This recursive decomposition is what makes the dynamic programming solution possible.
Overlapping Subproblems
A naive recursive implementation of LCS has exponential time complexity O(2^n) because it recomputes the same subproblems repeatedly. The LCS of two prefixes is needed multiple times across different recursive branches. Dynamic programming eliminates this redundancy by storing results in a memoization table. For sequences of length m and n, a standard DP approach fills an (m+1) × (n+1) matrix, reducing time complexity to O(mn). This property is why LCS is the textbook example for introducing DP.
Subsequence vs. Substring
A critical distinction: an LCS is a subsequence, not a substring. Characters must appear in the same relative order but do not need to be contiguous. For example, given AXY and AYX, the LCS is AX or AY (length 2), not XY. This non-contiguity is what makes LCS ideal for diff algorithms—it can skip over unchanged boilerplate to find the essential structural alignment between two document versions, even when new text is inserted in the middle of a paragraph.
Backtracking for Diff Output
The DP table alone only yields the length of the LCS. To produce the actual diff, a backtracking phase traces from the bottom-right cell back to the origin. Each move corresponds to an edit operation:
- Diagonal move: characters match (unchanged line)
- Up move: deletion from the first document
- Left move: insertion from the second document This backtrack produces the minimal edit script that transforms one document into the other, which is the foundation of the Unified Diff Format and legal redline generation.
Non-Uniqueness of Solutions
For any given pair of sequences, there may be multiple distinct LCS solutions of the same maximal length. For instance, ABC and ACB have two LCS results: AB and AC. This ambiguity matters in legal differencing because different valid alignments can produce semantically different redlines. Production systems often apply tie-breaking heuristics—such as preferring matches that preserve clause boundaries or align defined terms—to ensure the generated diff is legally coherent and not just mathematically minimal.
Hirschberg's Space Optimization
The classic DP approach requires O(mn) space to store the entire matrix, which becomes prohibitive for large legal documents. Hirschberg's algorithm reduces space complexity to O(min(m, n)) while maintaining O(mn) time. It uses a divide-and-conquer strategy: find the optimal midpoint of the alignment, recursively solve the left and right halves, and combine. This optimization is critical for comparing multi-hundred-page contracts without exhausting memory, making LCS viable in production legal AI pipelines.
Frequently Asked Questions
Explore the core mechanics and practical applications of the Longest Common Subsequence algorithm, the foundational dynamic programming technique that powers modern document comparison and redline analysis engines.
The Longest Common Subsequence (LCS) is a classic dynamic programming algorithm that identifies the longest sequence of characters, tokens, or lines that appear in the same relative order within two input sequences, though not necessarily contiguously. The algorithm constructs a two-dimensional matrix where each cell (i, j) stores the length of the LCS for the prefixes ending at position i in the first sequence and j in the second. It operates with a time complexity of O(m*n), where m and n are the lengths of the two sequences. The core recurrence relation is: if the elements match, LCS[i][j] = LCS[i-1][j-1] + 1; otherwise, LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1]). After populating the matrix, a traceback step reconstructs the actual subsequence by walking backwards from the bottom-right cell, following the path of optimal decisions. This traceback directly yields the minimal edit script—the set of insertions and deletions required to transform one document into the other—making LCS the computational backbone of the standard Unix diff utility and modern legal redline tools.
LCS vs. Related Algorithms
A technical comparison of the Longest Common Subsequence algorithm against other foundational sequence comparison and edit distance methods used in document differencing engines.
| Feature | Longest Common Subsequence (LCS) | Levenshtein Edit Distance | Myers Diff Algorithm |
|---|---|---|---|
Primary Objective | Find the longest shared subsequence preserving order | Compute minimum single-character edits to transform strings | Find the shortest edit script between two sequences |
Computational Complexity | O(n*m) time and space | O(n*m) time and space | O(ND) time, where D is edit distance |
Output Type | The common subsequence itself | Integer edit distance score | Minimal set of insert/delete operations |
Handles Block Moves | |||
Semantic Awareness | |||
Standard Unix Utility | |||
Optimal for Line-Level Diff | |||
Memory Optimization | Hirschberg variant reduces to O(min(n,m)) | Single-row optimization available | Linear space variant exists |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Core algorithms and concepts that build upon or directly relate to the Longest Common Subsequence (LCS) in the context of document comparison and version control.
Edit Distance (Levenshtein)
A quantitative metric measuring the minimum number of single-character operations (insertions, deletions, substitutions) required to transform one string into another. While LCS focuses on the preserved sequence, edit distance focuses on the cost of change. The relationship is direct: EditDistance = |A| + |B| - 2 * |LCS(A, B)|.
- Use Case: Fuzzy string matching and spell-checking.
- Contrast: LCS finds commonality; Levenshtein measures difference.
Myers Diff Algorithm
An O(ND) greedy algorithm that finds the shortest edit script between two sequences by exploring an edit graph. It is the foundational algorithm behind the standard Unix diff utility and directly relies on LCS logic to produce a minimal, human-readable patch.
- Mechanism: Traverses a grid to find the shortest path from the top-left to bottom-right corner.
- Output: A minimal set of insertions and deletions, which is the inverse of the LCS.
N-Gram Similarity
A text comparison method that decomposes documents into contiguous sequences of 'n' words or characters and measures their overlap. Unlike LCS, which requires strict sequential order, n-gram similarity can detect paraphrased or reordered content.
- Jaccard Index: A common metric for measuring n-gram set overlap.
- Advantage: More robust to block-level reordering than strict LCS.
Fuzzy Matching
A technique that identifies non-identical but similar strings across documents. It is crucial for aligning moved or reworded clauses that a strict LCS-based text comparison would miss. Fuzzy matching often uses edit distance or token-based ratios.
- Example: Matching 'The Purchaser shall indemnify' with 'The Buyer agrees to indemnify'.
- Application: Pre-processing step before running a semantic or structural diff.
Patch Generation
The process of creating a compact, machine-readable file containing only the differences between two documents. The LCS is the theoretical backbone for generating a minimal patch. The patch file stores the instructions (insertions and deletions) needed to transform the original into the modified version.
- Formats: Unified Diff Format, Context Diff.
- Function:
patch(original, diff_script) = modified.
Tree Edit Distance
An algorithm measuring the minimum-cost sequence of node insertions, deletions, and relabelings to transform one hierarchical structure into another. This extends LCS from a flat sequence problem to a structured, ordered tree problem, essential for comparing XML or Abstract Syntax Trees (ASTs).
- Zhang-Shasha Algorithm: A classic solution for ordered tree edit distance.
- Legal Use: Comparing the logical structure of contract clause hierarchies.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us