Sub topic 2
Why Brute Force Fails: 2^n Subsequences
This chapter assumes you can read Python, know Big-O notation, and know what a recursive function is. You should also remember from the previous chapter that a subsequence keeps elements in their original order but may skip any of them.
The most direct way to find a longest increasing subsequence (LIS) is to list every subsequence, throw away the ones that are not increasing, and keep the longest. That method is correct and easy to write. It also runs in exponential time. This chapter builds the brute-force solution, measures why it fails, and points out the structure in its wasted work that the dynamic program in the next chapter takes advantage of.
Counting the Subsequences
To form a subsequence, you go through the array one element at a time and decide whether that element is in or out. Each of the n elements gets two choices, and every combination of choices gives a different subsequence (counted by positions, not by values). That makes exactly 2^n subsequences, including the empty one and the whole array.
A bitmask records these choices compactly. Bit i of an integer mask is 1 if a[i] is included. As mask runs from 0 to 2**n - 1, it visits every subsequence once.
| Array length n | Subsequences 2^n | Rough Python time at 10^7 subsets/s |
|---|---|---|
| 10 | 1,024 | under 1 ms |
| 20 | 1,048,576 | about 0.1 s |
| 30 | 1,073,741,824 | about 2 minutes |
| 40 | about 1.1 × 10^12 | about 30 hours |
| 50 | about 1.1 × 10^15 | about 3.5 years |
| 100 | about 1.3 × 10^30 | far longer than the age of the universe |
The time column is generous, because checking one subsequence costs up to n steps and not one. Even so, the pattern is clear: each extra element doubles the work. Input sizes in practice are often 10^5 or more, so brute force can only ever serve as a teaching tool and a test oracle.
Brute Force with a Bitmask
def lis_bruteforce(a):
n = len(a)
best = 0
for mask in range(1 << n): # every subset of positions
prev = None
length = 0
ok = True
for i in range(n):
if (mask >> i) & 1: # a[i] is included
if prev is not None and a[i] <= prev:
ok = False # not strictly increasing
break
prev = a[i]
length += 1
if ok and length > best:
best = length
return best
print(lis_bruteforce([10, 9, 2, 5, 3, 7, 101, 18])) # 4
print(lis_bruteforce([])) # 0
print(lis_bruteforce([7, 7, 7])) # 1The outer loop runs 2^n times and the inner loop runs up to n times, so the total cost is O(n · 2^n). Memory use is O(1) beyond the input, because no subsequence is ever stored.
A few details are worth checking:
- Empty input.
range(1 << 0)isrange(1), so the loop visits only the empty mask and returns 0. That is the correct answer. - Duplicates. The test
a[i] <= prevrejects equal neighbours, so[7, 7, 7]gives 1. Changing it toa[i] < prevwould compute the longest non-decreasing subsequence, which gives 3. - Early break. The
breakmakes rejection faster, but it does not change the worst case. On a sorted array every mask is increasing, so nothing is rejected early.
Brute Force as Include/Exclude Recursion
The bitmask version tests every subset, including ones that already failed to be increasing at their first two elements. A recursive version can prune those. At index i it either skips a[i] or, if a[i] is larger than the last element taken, takes it.
def lis_recursive(a):
def go(i, prev):
# Best length obtainable from a[i:] given that the last taken value is prev
if i == len(a):
return 0
skip = go(i + 1, prev)
take = 0
if prev is None or a[i] > prev:
take = 1 + go(i + 1, a[i])
return max(skip, take)
return go(0, None)
print(lis_recursive([10, 9, 2, 5, 3, 7, 101, 18])) # 4Pruning helps on some inputs and does nothing on others. To see the difference, count the calls:
def count_calls(a):
calls = 0
def go(i, prev):
nonlocal calls
calls += 1
if i == len(a):
return 0
skip = go(i + 1, prev)
take = 0
if prev is None or a[i] > prev:
take = 1 + go(i + 1, a[i])
return max(skip, take)
go(0, None)
return calls
for n in (10, 15, 20):
inc = list(range(n))
dec = list(range(n, 0, -1))
print(n, count_calls(inc), count_calls(dec))
# 10 2047 66
# 15 65535 136
# 20 2097151 231On a strictly increasing array the "take" branch is always allowed. The call tree is then a full binary tree of depth n with 2^(n+1) − 1 nodes. On a strictly decreasing array, a take is possible only while nothing has been taken yet, so the tree is thin and the call count grows only quadratically. The worst case is still exponential, and Big-O analysis has to assume the worst case.
Where the Wasted Work Lives
Look at what go depends on. It is called with an index i and the last value taken, prev. Different sequences of choices often reach the same pair. For [1, 2, 3], taking 1 and then 2 leads to go(2, prev=2). Skipping 1 and then taking 2 leads to the same call. The recursion solves that subproblem twice and gets the same answer both times.
How many distinct subproblems exist? prev is always either "nothing taken" or one of the array's elements. If you identify it by the index of the element taken, there are n + 1 possibilities. i ranges over n + 1 values. That gives at most (n + 1)^2 distinct states, while the call tree can have up to 2^(n+1) − 1 nodes. For n = 20 that is at most 441 distinct questions asked about 2 million times.
Two caveats apply if you add memoization to the recursion above:
- Key the cache on the index of
prevand not its value. Keying on values works for this problem, but it hides the n + 1 bound, and it causes trouble in variants that need to know positions. - Python's default recursion limit is about 1000. Recursion depth here equals n, so memoized recursion fails on long inputs even when the time is fine. The iterative DP in the next chapter does not have this problem.
Brute Force Still Has a Job: Test Oracle
Brute force is too slow for real inputs, but it is short and obviously correct. That makes it the right reference for testing the faster algorithms later in this tutorial. Faster LIS code has subtle failure points: bisect_left versus bisect_right, ties between equal values, and reconstruction pointers. Comparing it against brute force on thousands of small random arrays catches these bugs quickly.
import random
def cross_check(trials=2000, max_n=10, max_val=5):
for _ in range(trials):
n = random.randint(0, max_n)
a = [random.randint(0, max_val) for _ in range(n)]
x, y = lis_bruteforce(a), lis_recursive(a)
assert x == y, (a, x, y)
print("all", trials, "trials agree")
cross_check()Keep max_val small compared with max_n. Small values force many duplicates, and duplicates are where strict and non-strict bugs show up. Keep max_n around 10 to 12 so each trial takes microseconds.
Summary of Costs
| Method | Time | Extra space | Notes |
|---|---|---|---|
| Bitmask enumeration | O(n · 2^n) | O(1) | Tests every subset, even hopeless ones |
| Include/exclude recursion | O(2^n) worst case | O(n) stack | Prunes non-increasing branches; still exponential on sorted input |
| Recursion with cache on (i, prev index) | O(n^2) | O(n^2) cache, O(n) stack | Bridge to the dynamic program |
Exercise
An array has 6 distinct elements in strictly increasing order. How many of its subsequences are strictly increasing, counting the empty one? How many are there if the 6 elements are in strictly decreasing order instead?
Show answer
Increasing order: every subset of positions is increasing, so there are 2^6 = 64. Decreasing order: only the empty subsequence and the 6 single elements qualify, so there are 7.
Exercise
Change one character in lis_bruteforce so that it returns the length of the longest non-decreasing subsequence. What does the modified version return for [1, 3, 3, 2, 3]?
Show answer
Change the test a[i] <= prev to a[i] < prev, so a subsequence is rejected only when a value strictly decreases. For [1, 3, 3, 2, 3] it returns 4, from the subsequence 1, 3, 3, 3.
Exercise
count_calls on a strictly increasing array of length n returns 2^(n+1) − 1. Explain why, and state how many distinct (i, prev index) states the calls actually cover.
Show answer
On increasing input both the skip and take branches are always allowed, so each call with i < n makes exactly two child calls. The result is a full binary tree of depth n, which has 2^(n+1) − 1 nodes. The distinct states number at most (n + 1)^2, because i has n + 1 values and the previously taken index has n + 1 options, counting "none". Since prev must come before i, the true count is about half that.