Sub topic 3
The O(n^2) Dynamic Program
This chapter assumes you can read Python and know Big-O notation. It also assumes you know the basic dynamic programming idea: solve small subproblems, store their answers, and combine them through a recurrence. You should already know what a strictly increasing subsequence is, and why listing all 2^n subsequences is too slow. Here we build the first practical algorithm: a dynamic program that runs in O(n^2) time and O(n) space.
Choosing the Right Subproblem
The hardest step in any dynamic program is picking what each table entry means. For LIS, the obvious choice does not work, so it helps to see why.
The tempting state that fails
Suppose you define best[i] as the length of the LIS within the prefix a[0..i]. To compute best[i], you would ask whether a[i] can extend the best subsequence of the earlier prefix. To answer that, you need to know the last value of that subsequence, and best[i-1] does not record it. The prefix [1, 5, 2, 3] shows the problem. An LIS of [1, 5] is [1, 5], which ends in 5. When 2 and then 3 arrive, neither can extend [1, 5], yet [1, 2, 3] is longer. A single length per prefix loses the information you need.
The state that works
Fix the ending position instead:
dp[i]= the length of the longest strictly increasing subsequence that ends exactly at index i, meaninga[i]is its last element.
This state includes the last value for free, because the last value is a[i]. Any subsequence that a[i] extends must end at some earlier index j with a[j] < a[i], and dp[j] already describes the best such subsequence.
The Recurrence
Every increasing subsequence ending at i is one of two kinds:
- The single element
[a[i]], with length 1. - An increasing subsequence ending at some
j < iwitha[j] < a[i], followed bya[i].
That gives the recurrence:
dp[i] = 1 + max(dp[j] for j < i if a[j] < a[i]), ordp[i] = 1if no suchjexists.
The answer to the whole problem is max(dp[0], ..., dp[n-1]). The LIS has to end somewhere, and the table covers every possible ending index.
Why the recurrence is correct
The argument rests on optimal substructure. Take a longest increasing subsequence ending at i, with length L > 1, and let j be the index of its second-to-last element. Remove a[i] and you have an increasing subsequence of length L - 1 ending at j. So dp[j] >= L - 1. If dp[j] were larger, you could append a[i] to that longer subsequence and get one longer than L ending at i, which is a contradiction. So dp[j] = L - 1, and the recurrence, which takes the maximum over all valid j, finds L.
The order of evaluation also matters. dp[i] depends only on entries with smaller indices, so filling the table left to right means every value you read has already been computed.
The Implementation
def lis_length_quadratic(a):
if not a:
return 0
dp = [1] * len(a) # dp[i] = length of LIS ending at index i
for i in range(len(a)):
for j in range(i):
if a[j] < a[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp)
print(lis_length_quadratic([10, 9, 2, 5, 3, 7, 101, 18])) # 4Each line maps to part of the derivation:
dp = [1] * len(a)is the base case. Every element on its own is an increasing subsequence of length 1.- The inner loop over
j in range(i)covers every possible predecessor. a[j] < a[i]enforces strict increase.dp[j] + 1 > dp[i]keeps the running maximum.max(dp)picks the best ending index.- The early return handles the empty list, where
max([])would raiseValueError.
Tracing the Example
Here is the table for a = [10, 9, 2, 5, 3, 7, 101, 18]. The "valid predecessors" column lists every earlier index j with a[j] < a[i].
| i | a[i] | Valid predecessors j (a[j]) | Best dp[j] | dp[i] |
|---|---|---|---|---|
| 0 | 10 | none | none | 1 |
| 1 | 9 | none | none | 1 |
| 2 | 2 | none | none | 1 |
| 3 | 5 | 2 (2) | 1 | 2 |
| 4 | 3 | 2 (2) | 1 | 2 |
| 5 | 7 | 2 (2), 3 (5), 4 (3) | 2 | 3 |
| 6 | 101 | 0, 1, 2, 3, 4, 5 | 3 (at j=5) | 4 |
| 7 | 18 | 0, 1, 2, 3, 4, 5 | 3 (at j=5) | 4 |
The maximum is 4, reached at both index 6 (ending in 101) and index 7 (ending in 18). The last entry happens to be maximal here, but that is a coincidence of this input, as the next section shows.
The DAG View
The DP can also be described as a graph problem. Make each index a node and draw an edge j → i whenever j < i and a[j] < a[i]. Edges only point forward in index order, so the graph has no cycles: it is a directed acyclic graph (DAG). An increasing subsequence is a path in this graph, and the LIS is the path with the most nodes. dp[i] is the longest path ending at node i, and the left-to-right loop processes the nodes in topological order.
This view explains the cost. In the worst case, a sorted input, every pair is an edge, so there are about n^2/2 edges and the DP examines each one. Faster algorithms in later chapters avoid looking at every edge.
Complexity
- Time: the inner loop runs
itimes for eachi. The total is0 + 1 + ... + (n-1) = n(n-1)/2comparisons, which is Θ(n^2) on every input, not just the worst case. - Space: one array of
nintegers, O(n).
In CPython, a pair of nested loops runs roughly 10^7 to 10^8 simple iterations per minute or faster, depending on the machine. As a rough guide, n = 1,000 (about 500,000 comparisons) finishes almost instantly, n = 10,000 (about 50 million) takes several seconds, and n = 100,000 is impractical. If a problem's limits go beyond a few thousand elements, you need the O(n log n) method.
Testing Against Brute Force
A small randomized test catches most off-by-one and comparison mistakes. The brute-force function below tries subset sizes from largest to smallest and returns the first size that has an increasing subsequence.
import random
from itertools import combinations
def lis_length_quadratic(a):
if not a:
return 0
dp = [1] * len(a)
for i in range(len(a)):
for j in range(i):
if a[j] < a[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp)
def lis_brute(a):
for r in range(len(a), 0, -1):
for idx in combinations(range(len(a)), r):
if all(a[idx[k]] < a[idx[k + 1]] for k in range(r - 1)):
return r
return 0
random.seed(1)
for _ in range(2000):
n = random.randint(0, 9)
a = [random.randint(0, 5) for _ in range(n)] # small range forces duplicates
assert lis_length_quadratic(a) == lis_brute(a), a
print("all tests passed")Drawing values from a small range matters. It produces many repeated values, which is where comparison bugs show up.
Common Errors
Returning dp[-1] instead of max(dp)
dp[n-1] only covers subsequences that end at the last element. For [1, 2, 3, 0], dp is [1, 2, 3, 1], so dp[-1] gives 1 while the correct answer is 3.
Using <= when the problem asks for strict increase
Writing a[j] <= a[i] silently changes the problem to longest non-decreasing subsequence. For [2, 2, 2], the strict answer is 1, but the <= version returns 3. Read the problem statement carefully, because "increasing" sometimes means non-decreasing. Later chapters cover this variant directly.
Initializing dp to 0
If dp starts at 0, an element with no valid predecessor gets length 0 instead of 1, and every chain built from it comes out one short. The base case is "the element alone," which has length 1.
Taking max(dp) on an empty list
max([]) raises ValueError. Either guard against empty input, as the implementation does, or write max(dp, default=0).
Comparing indices instead of values
Writing j < i inside the condition, where you meant a[j] < a[i], makes the condition always true, so the function returns n. The loop bound already guarantees j < i. The condition must compare values.
A Symmetric Formulation
You can run the DP in the other direction. Define start[i] as the length of the LIS that begins at index i, and fill the table from right to left:
start[i] = 1 + max(start[k] for k > i if a[k] > a[i]).
The overall answer is again the maximum entry. Combining both tables is useful: dp[i] + start[i] - 1 is the length of the longest increasing subsequence that passes through index i. An element belongs to some LIS exactly when this value equals the overall LIS length.
def lis_through_each_index(a):
n = len(a)
end = [1] * n
start = [1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i]:
end[i] = max(end[i], end[j] + 1)
for i in range(n - 1, -1, -1):
for k in range(i + 1, n):
if a[k] > a[i]:
start[i] = max(start[i], start[k] + 1)
return [e + s - 1 for e, s in zip(end, start)]
print(lis_through_each_index([10, 9, 2, 5, 3, 7, 101, 18]))
# [2, 2, 4, 4, 4, 4, 4, 4]The output shows that 10 and 9 are in no LIS, since their best value is 2 while the LIS length is 4. Every other element appears in at least one longest subsequence.
Exercise
Compute the dp array and the LIS length for a = [3, 1, 4, 1, 5, 9, 2, 6].
Show answer
dp = [1, 1, 2, 1, 3, 4, 2, 4]. Index 2 (value 4) extends 3 or 1 to get 2. Index 4 (value 5) extends 4 to get 3. Index 5 (value 9) extends 5 to get 4. Index 6 (value 2) extends 1 to get 2. Index 7 (value 6) extends 5 to get 4. The LIS length is max(dp) = 4, for example [3, 4, 5, 9] or [1, 4, 5, 6].
Exercise
Give an input of length 4 where returning dp[-1] gives the wrong answer, and explain why max(dp) is required.
Show answer
[5, 6, 7, 1] has dp = [1, 2, 3, 1], so dp[-1] is 1, but the LIS [5, 6, 7] has length 3. dp[i] only counts subsequences that end at index i, and the LIS can end at any index, so the answer is the maximum over all of them.
Exercise
How many times is the condition a[j] < a[i] evaluated for n = 1000, and does that count depend on the input values?
Show answer
n(n-1)/2 = 1000 * 999 / 2 = 499,500 times. The count does not depend on the values, because both loops always run their full ranges. Only the number of updates to dp[i] depends on the data.
Exercise
Modify the recurrence to compute the longest strictly decreasing subsequence, and state its value for [10, 9, 2, 5, 3, 7, 101, 18].
Show answer
Change the condition to a[j] > a[i]; everything else stays the same. The dp array becomes [1, 2, 3, 3, 4, 3, 1, 2], so the answer is 4, for example [10, 9, 5, 3].