LIS & LCS
Compute longest increasing and longest common subsequences and reconstruct the answers.
By Invicly Tech, , in Data Structures & Algorithms. About 11 minutes to read.
In short
The longest increasing subsequence and longest common subsequence are two of the most reused DP patterns. LIS has a simple O(n^2) DP and an O(n log n) method that keeps the smallest tail for each length. LCS fills a 2D table comparing prefixes of two sequences.
Explained simply
A subsequence is what you get by crossing out some items from a list but keeping the rest in their original order. From [3, 1, 4, 1, 5] you can get [3, 4, 5] or [1, 1, 5], but not [5, 3]. A substring or subarray is different: its items must sit next to each other.
The longest increasing subsequence, or LIS, is the longest subsequence where every item is bigger than the one before. In [3, 1, 4, 1, 5, 9, 2, 6], one LIS is [1, 4, 5, 9], length 4. Think of a stock price: LIS tells you the longest run of days you could pick where the price kept going up.
The longest common subsequence, or LCS, compares two sequences and finds the longest subsequence they share. For "ABCBDAB" and "BDCABA" it is 4 letters long, for example "BCBA". Comparing two versions of a file line by line works this way: the lines in the LCS stayed the same, and the rest were added or removed.
LIS has a simple O(n^2) DP and a clever O(n log n) method. LCS uses a 2D table in O(m x n). Both let you rebuild the actual subsequence, not just its length, if you keep a little extra information.
Press Play on a diagram to walk through it one step at a time.
- 13, 1
tails = [1]
- 24, 1
tails = [1, 4]
- 35, 9
tails = [1, 4, 5, 9]
- 42
Replace 4: [1, 2, 5, 9]
- 56
Replace 9: [1, 2, 5, 6], length 4
- LIS
- Russian doll envelopes
- Box stacking with sorted sides
- LCS of two permutations
- LCS
- Line-based file diff
- Longest palindromic subsequence
- Shortest common supersequence
- Insert or delete edit distance
In depth
The O(n^2) LIS and rebuilding it
Let dp[i] be the length of the longest increasing subsequence that ends exactly at index i. Every item alone has length 1. For each earlier j with a[j] < a[i], you could extend that subsequence, so dp[i] = 1 + max(dp[j]). The answer is max(dp), not dp[n - 1], because the best subsequence can end anywhere.
To get the subsequence itself, store prev[i] = the j that gave the max. Start at the index with the largest dp and follow prev back to -1, then reverse. This version is easy to adapt: counting how many LIS exist, using a weight per item, or a different comparison such as "divisible by" all fit the same double loop.
- dp[i] = 1 + max(dp[j] for j < i if a[j] < a[i])
- Answer is max(dp), not dp[-1]
- prev[i] stores the best j for rebuilding
Why the tails trick works
The O(n log n) method keeps tails[k] = the smallest possible last value of an increasing subsequence of length k + 1 seen so far. A smaller tail is always at least as good, because it is easier to extend.
tails stays sorted: a length-3 run ends with something larger than some length-2 run's end. So for each new x, binary search finds the first tail that is >= x. If there is none, x extends the longest run and is appended. Otherwise x replaces that tail, making that length easier to extend in future. n binary searches give O(n log n).
tails itself is not a valid subsequence; its values can come from different runs. To rebuild a real LIS, store the index of each tail and, for every element, the index of the tail before it at the moment it was placed.
- Strictly increasing
- Equal x replaces an equal tail
- [2, 2, 2] gives length 1
- Non-decreasing allowed
- Equal x goes after equal tails
- [2, 2, 2] gives length 3
LCS table and the walk back
dp[i][j] is the LCS length of a[:i] and b[:j]. If a[i - 1] == b[j - 1], that shared character ends a common subsequence: dp[i][j] = dp[i - 1][j - 1] + 1. Otherwise, at least one of the two last characters is unused, so dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]). Time and space are O(m x n).
To rebuild the string, start at (m, n). On a match, record the character and move diagonally. Otherwise move towards the larger neighbour, up or left. Stop when either index hits 0 and reverse what you collected. When up and left are equal, either choice gives a correct LCS, which is why different programs can print different but equally long answers.
- 1Start
i = m, j = n.
- 2Letters match?
Record it, move to (i-1, j-1).
- 3Else up >= left?
Move up to (i-1, j).
- 4Else
Move left to (i, j-1).
- 5Stop
When i or j is 0; reverse the result.
Problems that are secretly LIS or LCS
Several classics reduce to these two. The shortest common supersequence of a and b has length m + n - LCS. The fewest insertions and deletions (no replacements) to turn a into b is m + n - 2 x LCS. The longest palindromic subsequence of s is the LCS of s and its reverse.
When both inputs are permutations of the same distinct values, LCS becomes LIS: replace each value of b by its position in a, and the LCS is the LIS of that list, in O(n log n) instead of O(n^2). Russian doll envelopes (fit envelopes inside each other) is LIS after sorting by width ascending and, for equal widths, height descending, so two envelopes of the same width can never both be picked.
For huge inputs, Hirschberg's algorithm rebuilds an LCS in O(m x n) time but only O(min(m, n)) space.
Learn it in 4 short steps
About 55m each. Track them with a timer in your plan.
- 1Solve LIS in O(n^2) with DP~55m
- 2Solve LIS in O(n log n) with patience~55m
- 3Solve LCS with a 2D table~55m
- 4Reconstruct the subsequence from the table~55m
Key points
- LIS DP: dp[i] = 1 + max(dp[j]) for j < i with a[j] < a[i], O(n^2).
- Patience method: binary search into tails, O(n log n).
- LCS: O(m x n); match takes the diagonal plus one, else max of up or left.
- Reconstruct LCS by walking back from dp[m][n].
Key terms
Tap a card to flip it. 0/3 known
Examples
from bisect import bisect_left
def lis_length(nums): # O(n log n)
tails = []
for x in nums:
i = bisect_left(tails, x)
if i == len(tails): tails.append(x)
else: tails[i] = x
return len(tails)
def lcs(a, b): # O(m * n)
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]Getting an actual LIS in O(n log n)
On [3, 1, 4, 1, 5, 9, 2, 6], tails ends as [1, 2, 5, 6], which is not a subsequence in that order (2 comes after 9). So we also keep tails_idx (the index of each tail) and parent (for each element, the index of the element before it in its run). At the end, start from the last tail's index and follow parents back. This prints [1, 4, 5, 6], a real increasing subsequence of length 4.
from bisect import bisect_left
def lis_path(a):
tails, tails_idx, parent = [], [], [-1] * len(a)
for i, x in enumerate(a):
k = bisect_left(tails, x)
if k == len(tails): tails.append(x); tails_idx.append(i)
else: tails[k] = x; tails_idx[k] = i
parent[i] = tails_idx[k - 1] if k else -1
out, i = [], tails_idx[-1] if a else -1
while i != -1: out.append(a[i]); i = parent[i]
return out[::-1]
print(lis_path([3, 1, 4, 1, 5, 9, 2, 6])) # [1, 4, 5, 6]Printing the LCS string
For "ABCBDAB" and "BDCABA", fill the table as in the explainer, then walk back from the bottom-right corner. Matches add a letter and move diagonally; otherwise we move towards the larger neighbour, preferring up on ties. The letters come out backwards (A, B, C, B), so we reverse them to get BCBA.
def lcs_string(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):
dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(dp[i-1][j], dp[i][j-1])
out, i, j = [], m, n
while i and j:
if a[i-1] == b[j-1]: out.append(a[i-1]); i -= 1; j -= 1
elif dp[i-1][j] >= dp[i][j-1]: i -= 1
else: j -= 1
return "".join(reversed(out))
print(lcs_string("ABCBDAB", "BDCABA")) # BCBAQuick reference
- Subsequence keeps order but may skip items; substring must be contiguous
- LIS O(n^2): dp[i] = 1 + max(dp[j]) over j < i with a[j] < a[i]; answer max(dp)
- LIS O(n log n): bisect_left on tails for strict, bisect_right for non-decreasing
- tails gives the length only; keep indexes and parents to rebuild the sequence
- LCS: match takes diagonal + 1, else max(up, left); O(m x n)
- Longest palindromic subsequence = LCS(s, s[::-1])
- Insert/delete-only edit distance = m + n - 2 x LCS
- Envelopes: sort by width ascending, height descending, then LIS on heights
Common mistakes
- Treating the tails array as the actual LIS; only its length is guaranteed.
- Confusing subsequence with substring.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Return the length of the longest palindromic subsequence of s. Example: "bbbab" gives 4 ("bbbb").
- Exercise 2medium
Envelopes are [width, height]. One fits inside another only if both are strictly smaller. Return the most envelopes you can nest. Example: [[5,4],[6,4],[6,7],[2,3]] gives 3.
- Exercise 3hard
Count how many longest strictly increasing subsequences exist. Example: [1, 3, 5, 4, 7] gives 2 ([1,3,4,7] and [1,3,5,7]); [2, 2, 2, 2, 2] gives 5.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a subsequence and a substring?
- Both keep the original order. A substring must be contiguous (no gaps), while a subsequence may skip items. "ace" is a subsequence of "abcde" but not a substring.
- Is the longest increasing subsequence unique?
- Not always. [1, 3, 2, 4] has two LIS of length 3: 1, 3, 4 and 1, 2, 4. Algorithms return one of them depending on tie-breaking.
- How does diff find changed lines?
- It treats each line as one symbol and finds a longest common subsequence of lines, or an equivalent shortest edit script. Lines outside it are shown as added or removed. git diff uses the Myers algorithm, which is fast when files are similar.
- Can LCS be done faster than O(m x n)?
- Not by much. The best known general methods only save a logarithmic factor, and researchers believe nothing dramatically faster exists. Special cases are faster, such as two permutations, which reduce to LIS in O(n log n).