Sub topic 1
What Is a Subsequence?
Every later chapter in this tutorial builds on one idea: the subsequence. Before you can compute the longest common subsequence of two strings, you need a precise definition of a subsequence. You also need to know how it differs from a substring and why there are so many of them. This chapter covers those three points and gives you small tools to test your understanding.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python syntax, including lists, loops, functions, and generators.
- Zero-based indexing and slicing of strings and lists.
- Big-O notation for time and space, at least for simple loops.
Recursion and two-dimensional lists come up in later chapters. You do not need them here.
The Definition
A sequence is an ordered list of elements, such as the characters of a string, the items of a Python list, or the lines of a file. Take a sequence t of length n. A subsequence of t is what remains after you delete zero or more elements and keep the rest in their original order.
Formally, s is a subsequence of t when there exist indices
0 <= i_1 < i_2 < ... < i_k < nsuch that s = t[i_1] t[i_2] ... t[i_k]. The indices must be strictly increasing. That one condition is the whole definition. Gaps between the indices are allowed, but you cannot reorder elements.
Two edge cases follow directly:
- The empty sequence (k = 0) is a subsequence of every sequence.
- Every sequence is a subsequence of itself (keep all indices).
A Worked Example
Let t = "ABCBDAB". Its indices are:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Character | A | B | C | B | D | A | B |
"BCDB"is a subsequence. Pick indices 1, 2, 4, 6."ACB"is a subsequence. Pick indices 0, 2, 3 (or 0, 2, 6)."AAB"is a subsequence. Pick indices 0, 5, 6."DC"is not a subsequence. The only D is at index 4 and the only C is at index 2, and 2 comes before 4.
Subsequence vs. Substring
A substring (also called a contiguous subsequence, or a subarray for lists) is a subsequence whose indices are consecutive: i_2 = i_1 + 1, i_3 = i_2 + 1, and so on. In Python, a substring is exactly a slice t[i:j].
So every substring is a subsequence, but most subsequences are not substrings.
| Candidate | Substring of "ABCBDAB"? | Subsequence of "ABCBDAB"? | Reason |
|---|---|---|---|
| `"BDAB"` | Yes | Yes | Indices 3, 4, 5, 6 are consecutive |
| `"BCDB"` | No | Yes | Indices 1, 2, 4, 6 have gaps |
| `"ABD"` | No | Yes | Indices 0, 1, 4 (or 0, 3, 4) |
| `"DC"` | No | No | Order is reversed |
| `""` | Yes | Yes | Empty slice / empty index set |
The difference matters for the problems you will solve. Longest common substring asks for an unbroken run shared by both inputs. Longest common subsequence allows gaps. The two problems have similar-looking tables but different recurrences, and a later chapter compares them directly.
Testing Whether One Sequence Is a Subsequence of Another
Checking whether s is a subsequence of t does not need dynamic programming. A greedy two-pointer scan is enough. Walk through t once and advance a pointer into s each time you see the next character you need.
def is_subsequence(s, t):
"""Return True if s is a subsequence of t. Works for strings and lists."""
i = 0
for item in t:
if i < len(s) and s[i] == item:
i += 1
return i == len(s)
t = "ABCBDAB"
for s in ["BCDB", "ACB", "AAB", "DC", "AAA", "BBB", ""]:
print(f"{s!r:7} -> {is_subsequence(s, t)}")
# Sequences don't have to be strings: lines of a file work the same way.
old = ["import os", "def main():", " pass"]
print(is_subsequence(["import os", " pass"], old)) # TrueOutput:
'BCDB' -> True
'ACB' -> True
'AAB' -> True
'DC' -> False
'AAA' -> False
'BBB' -> True
'' -> True
TrueThis runs in O(n) time for |t| = n and O(1) extra space.
Why Greedy Is Correct
Taking the earliest match for each character never hurts. Suppose some valid index choice matches s[0] at position p, and the greedy scan matches it at an earlier position q <= p. Every position after p is also after q, so the rest of that valid choice still works when s[0] is matched at q. Repeat the argument for each character. If any valid index sequence exists, the greedy scan finds one.
This greedy check answers "is s a subsequence of t?" It does not help you find the longest sequence common to two inputs, because then neither side is fixed. That harder question is what the rest of the tutorial is about.
Counting Subsequences
Each subsequence of t corresponds to a choice of which indices to keep. With n positions, each one is either kept or deleted, so there are exactly 2^n index subsets. Substrings are far fewer. A non-empty substring is fixed by its start and end, which gives n(n+1)/2 choices, plus the empty one.
When t has repeated characters, different index subsets can spell the same string. For example, indices {0, 2, 3} and {0, 2, 6} both give "ACB". The number of distinct subsequences is therefore at most 2^n. In the worst case it is still exponential: if all n characters are different, every index subset produces a different string.
The script below enumerates everything for "ABCBDAB" by brute force:
from itertools import combinations
def all_subsequences(t):
"""Yield one subsequence per index subset (2**len(t) results, with repeats)."""
for k in range(len(t) + 1):
for idx in combinations(range(len(t)), k):
yield "".join(t[i] for i in idx)
def all_substrings(t):
"""Return the set of distinct substrings, including the empty string."""
subs = {""}
for i in range(len(t)):
for j in range(i + 1, len(t) + 1):
subs.add(t[i:j])
return subs
t = "ABCBDAB"
subseqs = list(all_subsequences(t))
distinct_subseqs = set(subseqs)
substrings = all_substrings(t)
print(len(subseqs)) # 128 index subsets = 2**7
print(len(distinct_subseqs)) # 102 distinct subsequence strings
print(len(substrings)) # 25 distinct substrings
print(substrings <= distinct_subseqs) # True: every substring is a subsequence| Quantity for "ABCBDAB" (n = 7) | Count | Growth in n |
|---|---|---|
| Index subsets | 128 | 2^n |
| Distinct subsequences | 102 | Up to 2^n |
| Distinct substrings (with empty) | 25 | At most n(n+1)/2 + 1 |
Adding one character to t roughly doubles the number of subsequences. For a 50-character string that means about 10^15 index subsets, which is far too many to list. This growth is why the next chapters avoid enumerating subsequences and turn to a smarter method.
Common Mistakes
- Treating subsequence as substring. Answering
"BCDB"is not in"ABCBDAB"because"BCDB" in tisFalse. Python'sinoperator on strings tests for substrings only. - Ignoring order. Checking only that every character of
sappears int, for example with sets, accepts"DC". - Ignoring multiplicity. Using sets or counters without order also accepts or rejects the wrong cases when characters repeat.
- Forgetting the empty sequence. Base cases in later recurrences depend on the empty subsequence having length 0 and being common to everything.
- Assuming strings only. The definition applies to any sequence whose elements can be compared for equality. Diff tools use lines as elements, not characters.
Exercises
Exercise
For t = "ABCBDAB", classify each of "CBDA", "BAB", "CA B" without the space, i.e. "CAB", and "DD" as substring, subsequence only, or neither.
Show answer
"CBDA" is a substring (indices 2-5, which also makes it a subsequence). "BAB" is a subsequence only (indices 1, 5, 6 or 3, 5, 6). "CAB" is a subsequence only (indices 2, 5, 6). "DD" is neither, because t has only one D.
Exercise
A string t has length n and all its characters are different. How many distinct subsequences does it have, including the empty one, and how many distinct substrings, including the empty one?
Show answer
2^n distinct subsequences, because each index subset gives a different string when no characters repeat. There are n(n+1)/2 + 1 distinct substrings: one for each (start, end) pair with start <= end, plus the empty string.
Exercise
Someone writes is_subsequence(s, t) as all(ch in t for ch in s). Give an input where it returns the wrong answer and explain the bug.
Show answer
s = "DC", t = "ABCBDAB" returns True, but "DC" is not a subsequence. The expression checks only that each character occurs somewhere in t. It ignores order and multiplicity, so it also wrongly accepts s = "AAA". A correct check must search for each character after the position where the previous one was matched.
Exercise
What is the time complexity of the two-pointer is_subsequence(s, t) with |s| = m and |t| = n, and why does it never need to backtrack?
Show answer
O(n) time and O(1) extra space, since it scans t once (m <= n for any True answer, and the loop never exceeds n steps). It never backtracks because matching each character of s at its earliest possible position leaves the most room for the remaining characters. If any valid match exists, the greedy one also succeeds.