Introduction
In our last lesson, we tackled the 0/1 Knapsack pattern, where the decision for each item was a binary "take it or leave it". You saw how the recurrence relation, which depends only on the previous row's results, allows for space optimization using a 1D array with a backward-iterating inner loop.
This lesson introduces another fundamental 2D DP pattern: sequence comparison. The learning outcome is to solve problems where you compare two sequences (typically strings) to find an optimal alignment or transformation, such as the Longest Common Subsequence and Edit Distance.
These problems are cornerstones of technical interviews. Your task will be to define a 2D DP state, dp[i][j], that represents the solution for prefixes of the two input strings. Mastering this pattern is crucial for demonstrating the structured thinking expected at the Staff+ level.
1. Longest Common Subsequence (LCS)
The first canonical problem in this category is finding the Longest Common Subsequence. It's essential to first be precise about what a "subsequence" is.
A subsequence is formed by deleting zero or more characters from a string, keeping the remaining characters in their original relative order. For example, "ace" is a subsequence of "abcde", but "aec" is not. This is different from a substring, which must be contiguous.
Given two strings, text1 and text2, our goal is to find the length of the longest subsequence that is common to both.
From Recursion to DP
The key to solving this with DP is to break it down into subproblems. Consider the strings text1 and text2. Let's look at their last characters.
-
Case 1: The last characters match.
Iftext1[i] == text2[j], then this character must be part of the LCS. The length of the LCS is1 +the LCS of the strings without these last characters (text1up toi-1andtext2up toj-1). -
Case 2: The last characters do not match.
Iftext1[i] != text2[j], the common subsequence cannot include both. We have two choices:- Find the LCS of
text1up toi-1andtext2up toj. - Find the LCS of
text1up toiandtext2up toj-1.
We take the maximum of these two results.
- Find the LCS of
This recursive structure, with its overlapping subproblems, is perfectly suited for dynamic programming. The following video provides an excellent walkthrough, starting from this recursive intuition and building up to the 2D DP table.
Longest Common Subsequence (2 Strings) - Dynamic Programming & Competing Subproblems
This video from Back To Back SWE is one of the clearest explanations of LCS available. It starts by building a recursion tree to help you visualize the subproblems, then translates that logic directly into filling a DP table.
Please watch from the beginning to 23:18. Pay close attention to: The definition of a subsequence (00:00 - 02:15). The recursive breakdown based on matching/mismatching the last characters (02:15 - 13:09). This is the core logic. How this logic maps to filling the 2D DP table, cell by cell (13:09 - 23:18).
The DP State and Recurrence
As the video explains, we can formalize this with a 2D array, dp, where dp[i][j] stores the length of the LCS for text1[0...i-1] and text2[0...j-1].
The recurrence relation is:
- If
text1[i-1] == text2[j-1]: - If
text1[i-1] != text2[j-1]:
The base cases are dp[i][0] = 0 and dp[0][j] = 0, as the LCS with an empty string is always 0.

For a clean, bottom-up implementation in Go, the following resource is excellent.
1143. Longest Common Subsequence - Solution & Explanation
This NeetCode solution page provides several implementations for LCS. We'll focus on the bottom-up tabular approach, which directly implements the logic we've just discussed.
Please read the section '3. Dynamic Programming (Bottom-Up)'. Focus on the Go implementation. Note how the nested loops build the dp table and how the if/else block directly corresponds to the recurrence relation we defined.
2. Edit Distance
A closely related problem is Edit Distance (often called Levenshtein Distance). The goal is to find the minimum number of operations required to convert one string into another.
The allowed operations are:
- Insert a character.
- Delete a character.
- Replace a character.
Each operation has a cost of 1.
The DP Recurrence for Edit Distance
Like LCS, we define dp[i][j] as the minimum edit distance between the first i characters of word1 and the first j characters of word2.
Let's consider the last characters, word1[i-1] and word2[j-1].
-
Case 1: The last characters match.
Ifword1[i-1] == word2[j-1], no operation is needed for these characters. The cost is the same as the edit distance for the strings without them:dp[i][j] = dp[i-1][j-1]. -
Case 2: The last characters do not match.
We must perform one operation. We want the one with the minimum cost.- Replace
word1[i-1]withword2[j-1]. The cost is1 +the cost of convertingword1[0...i-2]toword2[0...j-2]. This corresponds to1 + dp[i-1][j-1]. - Delete
word1[i-1]. We then need to convertword1[0...i-2]toword2[0...j-1]. This corresponds to1 + dp[i-1][j]. - Insert
word2[j-1]intoword1. We now need to convertword1[0...i-1]toword2[0...j-2]. This corresponds to1 + dp[i][j-1].
- Replace
The recurrence is the minimum of these three choices:

This video will help you build intuition for these three choices.
Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)
Let's watch another Back To Back SWE video, this time on Edit Distance. It clearly explains what the three operations (insert, delete, replace) correspond to in the DP table.
Please watch the following segments: Problem definition (00:32 - 01:38). The four situations, especially the three operations when characters mismatch (03:02 - 07:40). This is the core logic. The beginning of the DP table walk-through to see how the base cases (comparisons with an empty string) are handled (07:40 - 10:02).
Go Implementation and Optimization
For a Go-centric developer, seeing this implemented idiomatically is key. The following article provides an excellent, progressive explanation from a naive recursive solution to a highly optimized bottom-up approach in Go.
Edit distance, benchmarks, and profiling in Go
This article by Kyle Kizirian is a fantastic deep dive into implementing and optimizing Edit Distance in Go. It's a perfect resource for understanding the implementation details at a Staff-engineer level.
Please read these two sections: The section beginning 'So what if we did this in the reverse order?'. This introduces the 'bottom-up' iterative solution using a 2D dist matrix. The next section, beginning 'Let's re-examine our bottom-up implementation.'. This details the space optimization to use only O(min(m,n)) space, a key technique that builds on what you learned in the 0/1 Knapsack lesson. \nFocus on how the code translates the DP recurrence into an iterative solution.
The optimized bottom-up Go code from the article is a great example of an interview-ready solution that is both correct and efficient.
Comparing LCS and Edit Distance
It's helpful to explicitly compare the two recurrence relations when characters at i-1 and j-1 do not match:
-
LCS:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])- We are trying to maximize a score (length).
- The choices are to ignore the character from
text1or ignore the character fromtext2and find the best outcome from the subproblems.
-
Edit Distance:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])- We are trying to minimize a cost (number of edits).
- The choices map to three concrete operations: delete (
dp[i-1][j]), insert (dp[i][j-1]), or replace (dp[i-1][j-1]). We add 1 for the cost of the chosen operation.
Understanding this subtle difference in the recurrence is key to solving variations of these problems.
Conclusion
In this lesson, we explored the sequence comparison DP pattern through its two most famous examples: Longest Common Subsequence and Edit Distance.
Key Takeaways:
- DP State: For problems comparing two sequences,
word1andword2, the statedp[i][j]almost always represents the optimal solution for the prefixesword1[0...i-1]andword2[0...j-1]. - Recurrence Logic: The core of the solution lies in defining the state transition based on whether
word1[i-1]andword2[j-1]match.- If they match, you typically carry over the solution from the smaller subproblem
dp[i-1][j-1]. - If they don't match, you take the
maxorminof the outcomes of different choices (e.g., skip a character in LCS, or perform an operation in Edit Distance).
- If they match, you typically carry over the solution from the smaller subproblem
- Space Optimization: Like other 2D DP problems, if the calculation for row
ionly depends on rowi-1, you can optimize the space from to .
Preview of the Next Lesson:
We will continue our exploration of DP on strings by focusing on a specific sub-pattern: palindromes. You will learn to solve problems like Longest Palindromic Subsequence, which cleverly reduces to an LCS problem, and other variations that use a slightly different DP state definition.