LeetCode 1143 · Medium

Longest Common Subsequence Explained (LeetCode 1143)

Updated Nov 27, 2026 · 3 min read

Fill a grid where dp[i][j] is the longest common subsequence of the first i characters of a and the first j of b. If the last characters match, take the diagonal plus 1; if not, take the max of the cell above and the cell to the left. The bottom-right cell is the answer, in O(n*m) time and space.

Watch onYouTubeInstagram

Key points

  • ●Testing every subsequence is O(2^n): 32 sub-routes for just 5 stops.
  • ●Compare the last characters: a match keeps it, a mismatch drops one side.
  • ●Match: dp[i][j] = dp[i-1][j-1] + 1. Mismatch: max(dp[i-1][j], dp[i][j-1]).
  • ●Row 0 and column 0 are 0, because an empty string shares nothing.
Step-by-step visual sheet: Longest Common Subsequence
The full visual sheet, made with Edithly.Open the interactive sheet

The riddle: two maps, one hike

Mia and Jo are hiking the same trail with different maps.

  • Mia's map has 5 stops: bridge, cabin, lake, peak, falls.
  • Jo's map has 4: cabin, bridge, lake, falls.

They can skip stops, but nobody walks back. What's the largest number of stops they can visit together?

The answer is 3: bridge, lake, falls. That's LeetCode 1143, Longest Common Subsequence. You get two strings and return the length of the longest sequence of characters that shows up in both, in the same order. Characters don't have to sit next to each other, but you can't reorder them. If nothing's shared, the answer is 0.

Write each stop as its first letter and the maps become a = "bclpf" and b = "cblf".

The slow way: test every sub-route

You could list every way to pick stops from Mia's route and check each one against Jo's. Five stops give 32 sub-routes. A thousand stops would never finish. That's O(2^n), and worse, it solves the same smaller pairs of routes over and over.

The idea: compare the last stops

Flip it around and start from the end of both maps.

  • The last stops match (falls and falls): keep it, and step both maps back one stop. The answer is 1 plus whatever the shorter routes share.
  • They don't match (peak and lake): at least one of them isn't in the shared route. So drop Mia's last stop, or drop Jo's, try both, and keep the longer result.

Each of those smaller questions is a cell in a grid, so nothing gets solved twice. That's step 3 of the visual sheet above: match means diagonal plus one, mismatch means max of up and left.

Trace it: the grid

Rows are Mia's stops, columns are Jo's. Each cell holds the best answer for the routes up to that row and column.

cabin bridge lake falls
bridge 0 1 1 1
cabin 1 1 1 1
lake 1 1 2 2
peak 1 1 2 2
falls 1 1 2 3

Lake meets lake and takes the diagonal 1 plus 1, which is 2. Falls meets falls and takes the diagonal 2 plus 1, which is 3. The bottom-right corner is the answer.

The code in Python

def longest_common_subsequence(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[m][n]

The grid is one row and one column bigger than the strings. Row 0 and column 0 stay 0, because an empty route shares nothing. Run it on "bclpf" and "cblf" and it returns 3.

Complexity

  • Time: O(n*m), one cell per pair of positions.
  • Space: O(n*m) for the grid.

You go from 2 to the n down to n times m.

The trap to watch for

The off-by-one. dp[i][j] describes the first i characters, so the characters you compare are a[i - 1] and b[j - 1], not a[i] and b[j]. Mix those up and you'll either crash or compare the wrong letters.

The other trap is treating a mismatch like a reset to 0. That's the rule for longest common substring, where the run must be unbroken. Here a mismatch just means "skip one side", so you carry forward the better of up and left.

Want to test yourself? Swap Jo's cabin for a peak and work out how many stops they can share now.

Frequently asked questions

What is the difference between a subsequence and a substring?

A substring has to be one unbroken piece. A subsequence can skip characters, as long as the ones it keeps stay in their original order. In 'bclpf', 'blf' is a subsequence but not a substring.

What is the time complexity of Longest Common Subsequence?

The dp grid takes O(n*m) time and O(n*m) space, where n and m are the two string lengths. Trying every subsequence is O(2^n).

Why does a match use the diagonal cell?

When both last characters match, you keep that shared character and solve the two shorter strings without it. That's the cell one row up and one column left, plus 1 for the character you kept.

What do you return if one string is empty?

0. The first row and first column of the grid stay 0 for exactly this reason, so the code handles it without a special case.

Turn any problem or document into a visual sheet like this one

Paste a LeetCode problem, a PDF or a link into Edithly and get a step-by-step sheet you can study, share or quiz yourself on.

Make this sheet in Edithly, free