Sub topic 3
Why Brute Force Does Not Scale
This chapter assumes you know basic Python, including lists, loops, and functions. It also assumes you can read Big-O notation and already know what a subsequence is and what the LCS problem asks. Here we write the most direct algorithm possible, which is to try every candidate. Then we measure how its cost grows. That growth is the reason the rest of this tutorial uses dynamic programming.
The Obvious Algorithm
Given strings a (length m) and b (length n), the brute-force method looks like this:
- Generate every subsequence of
a. - For each one, check whether it is also a subsequence of
b. - Keep the longest one that passes.
There is a small improvement that costs nothing. If we generate candidates from longest to shortest, the first candidate that passes is an answer, and we can stop.
Representing a subsequence as a choice of indexes
A subsequence of a is fully described by the set of positions it keeps. For "ABC", keeping positions {0, 2} gives "AC". Every subset of positions gives a valid subsequence, because keeping positions in increasing order preserves the original order. So the candidates correspond one-to-one with subsets of {0, 1, ..., m-1}, and there are 2^m subsets.
Checking a candidate against the other string
To test whether s is a subsequence of t, scan t once from left to right and match the characters of s in order. This greedy scan is correct. Matching each character of s at its earliest possible position in t leaves the most room for the characters after it. The scan costs O(n).
A Working Implementation
from itertools import combinations
def is_subsequence(s, t):
it = iter(t)
# "ch in it" advances the iterator until it finds ch, consuming t left to right.
return all(ch in it for ch in s)
def lcs_brute_force(a, b):
# Enumerate over the shorter string: 2**min(m, n) candidates instead of 2**max(m, n).
if len(a) > len(b):
a, b = b, a
for k in range(len(a), -1, -1): # longest candidates first
for idx in combinations(range(len(a)), k):
candidate = "".join(a[i] for i in idx)
if is_subsequence(candidate, b):
return candidate # first hit at size k is optimal
return ""
result = lcs_brute_force("ABCBDAB", "BDCABA")
print(result, len(result)) # BDAB 4itertools.combinations yields index tuples in increasing order, so each tuple is a valid subsequence. The loop over k runs from len(a) down to 0. The empty string always passes, so the function always returns.
Measuring the Cost
The worst case
Early stopping helps only when a long common subsequence exists. In the worst case the two strings share no characters. Then every size from m down to 1 fails, and the loop checks all 2^m candidates before the empty string passes.
The total work is the sum over sizes k of C(m, k) candidates. Each candidate costs O(k) to build and O(n) to check:
- Candidates: the sum of C(m, k) over k = 0..m is 2^m.
- Per candidate: O(m + n).
- Total: O((m + n) · 2^m), with m the shorter length after the swap.
Here is an instrumented version that counts candidates instead of returning the answer:
from itertools import combinations
import time
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)
def count_candidates(a, b):
checked = 0
for k in range(len(a), -1, -1):
for idx in combinations(range(len(a)), k):
checked += 1
if is_subsequence("".join(a[i] for i in idx), b):
return checked
return checked
for m in range(4, 21, 4):
a, b = "A" * m, "B" * m # no shared characters: worst case
start = time.perf_counter()
n_checked = count_candidates(a, b)
elapsed = time.perf_counter() - start
print(f"m={m:2d} candidates={n_checked:>9,} time={elapsed:.3f}s")On a typical laptop, the line for m = 20 checks 1,048,576 candidates and takes on the order of a second. Each extra character doubles that. Extrapolated at a generous 10 million candidate checks per second:
| Shorter length m | Candidates (2^m) | Approximate time |
|---|---|---|
| 20 | 1,048,576 | 0.1 seconds |
| 30 | about 1.07 billion | about 2 minutes |
| 40 | about 1.1 trillion | about 30 hours |
| 50 | about 1.1 quadrillion | about 3.5 years |
| 60 | about 1.15 quintillion | about 3,600 years |
Two 60-character strings are tiny inputs. A single line of source code can be that long, and a diff tool compares files with thousands of lines.
The best case is misleading
If a == b, the first candidate (all of a) passes, and the run costs O(m + n). A quick test on similar strings can make brute force look fast. Always judge an algorithm by its worst case, or at least by realistic inputs. Strings that share a short LCS force the search through almost every size before it succeeds. In that case the run costs nearly as much as the disjoint case.
Tempting Fixes That Do Not Help Enough
Deduplicating candidates
When a has repeated characters, different index sets produce the same string. For example, "AAAA" has 16 index subsets but only 5 distinct subsequences. You could store already-checked strings in a set and skip repeats. This helps with repetitive strings, but it fails in the general case:
- If the characters of
aare all different, all 2^m subsequences are distinct, so nothing is skipped. - The set itself can grow to exponential size, which trades time for memory you do not have.
Filtering characters first
Characters of a that never appear in b can never be part of a common subsequence. Removing them first is a valid and cheap step, O(m + n) with a set. It turns the disjoint-strings worst case into instant work. But if every character of a appears somewhere in b, nothing is removed. Take a = "AB" * 20 and b = "BA" * 20: they use the same alphabet, the filter removes nothing, and 2^40 candidates remain.
Enumerating from the other side
Picking the shorter string to enumerate gives 2^min(m, n) instead of 2^max(m, n). That is a real gain when the lengths differ a lot, and the implementation above already does it. It is still exponential.
Where the Waste Comes From
Brute force treats each candidate as an independent question, so it repeats the same work many times. Consider the candidates "BDAB" and "BDAC". Checking either one against b starts by matching "BDA", and the matching work for that shared prefix is done twice. With 2^m candidates, shared prefixes and suffixes repeat a very large number of times.
The efficient solution comes from asking about prefixes of the input strings instead of whole subsequences of a. A question of the form "what is the LCS of the first i characters of a and the first j characters of b?" has only (m + 1)(n + 1) possible versions. If the answer to each version can be built from smaller versions, the total work drops from 2^m to about m · n. The next chapter shows that this decomposition exists and derives the recurrence from it.
Summary
- A string of length m has 2^m subsequences, one for each subset of positions.
- Checking one candidate against
btakes O(n) with a greedy scan. - Brute force costs O((m + n) · 2^m) in the worst case, which is impractical once the shorter string has about 40 characters.
- Deduplication, character filtering, and enumerating the shorter string help on some inputs but stay exponential.
- The waste comes from re-solving shared pieces of work. Prefix subproblems remove that waste.
Exercise
Strings a and b both have length 25 and contain no common characters. Exactly how many candidates does lcsbruteforce check, and what does it return?
Show answer
It checks all 2^25 = 33,554,432 candidates. Every non-empty candidate fails, and the empty string, checked last at k = 0, passes. The function returns "".
Exercise
Someone proposes removing every character of a that does not occur in b before running brute force, and claims this makes the algorithm polynomial. Give an input that disproves the claim, and state the number of candidates it still requires.
Show answer
Use a = "AB" 15 and b = "BA" 15. Every character of a appears in b, so the filter removes nothing. The LCS has length 29, so the search fails at size 30 and finds an answer at size 29 only after checking up to 1 + 30 = 31 candidates in the best order. To get an exponential count, use a pair where the LCS is short but every character is shared, such as a = "A" 15 + "B" 15 and b = "B" 15 + "A" 15. The LCS there has length 15, and the search must first reject every candidate of size 30 down to 16. That is the sum of C(30, k) for k = 16 to 30, about 4.6 × 10^8 candidates, so the filtered algorithm is still exponential.
Exercise
Why is it correct to return the first candidate that passes when sizes are enumerated from longest to shortest, even though several different common subsequences may have that size?
Show answer
The LCS problem asks for a common subsequence of maximum length. Every larger size has already been tried and failed, so no common subsequence is longer than the first one found. Any other common subsequence of the same size is equally valid, so returning the first one is correct. Which one comes out depends only on enumeration order.