Sub topic 11
Counting All Longest Increasing Subsequences
Finding one longest increasing subsequence (LIS) answers "how long?" and "which one?". Some problems ask a third question: how many different subsequences reach that maximum length? This chapter extends the O(n^2) dynamic program from earlier so that it tracks a count next to each length. It then covers what "different" means, the mistakes people usually make, and a faster O(n log n) version.
This chapter assumes you know the O(n^2) LIS dynamic program, where dp[i] is the length of the LIS ending at index i. It also assumes basic Python and Big-O notation. The last section uses a Fenwick tree with coordinate compression, which the next chapter covers in full. You can skim that section for now.
What Exactly Are We Counting?
Before writing code, decide what counts as two different subsequences. The standard definition, used by LeetCode 673 ("Number of Longest Increasing Subsequence") and most textbooks, counts index sequences. Two subsequences are different if they use different positions in the array, even when the values they spell out are identical.
Take [1, 2, 2, 3] with strictly increasing order. The LIS length is 3, and two index sequences reach it:
| Indices | Values |
|---|---|
| 0, 1, 3 | 1, 2, 3 |
| 0, 2, 3 | 1, 2, 3 |
By index the count is 2. By distinct value sequence the count is 1. The algorithm in this chapter counts by index. Counting distinct value sequences needs extra deduplication, which the exercises explore.
Extending the Recurrence
The O(n^2) DP gives every index i a value length[i], the length of the longest strictly increasing subsequence ending at i. Next to it, keep count[i], the number of index sequences that end at i and have exactly length length[i].
Every such subsequence is either the element a[i] alone, or a longest-ending-at-j subsequence for some j < i with a[j] < a[i], followed by a[i]. That gives three cases when you look at a predecessor j:
a[j] >= a[i]:jcannot come beforei. Skip it.length[j] + 1 > length[i]: you found a strictly longer chain. The old count no longer applies, so replace it:count[i] = count[j].length[j] + 1 == length[i]: you found more chains of the current best length. Add them:count[i] += count[j].
Both arrays start at 1, because each element alone is one subsequence of length 1.
At the end, the LIS can end at any index. The answer is the sum of count[i] over every i where length[i] equals the overall maximum.
The Implementation
def count_lis(a):
n = len(a)
if n == 0:
return 0
length = [1] * n
count = [1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i]:
if length[j] + 1 > length[i]:
length[i] = length[j] + 1
count[i] = count[j]
elif length[j] + 1 == length[i]:
count[i] += count[j]
best = max(length)
return sum(c for l, c in zip(length, count) if l == best)
print(count_lis([1, 3, 5, 4, 7])) # 2
print(count_lis([2, 2, 2, 2, 2])) # 5
print(count_lis([1, 2, 2, 3])) # 2This runs in O(n^2) time and O(n) extra space, the same as the length-only DP. The work per pair is still constant.
Tracing an Example
Here is the trace for a = [1, 3, 5, 4, 7]:
| i | a[i] | Contributing predecessors j | length[i] | count[i] |
|---|---|---|---|---|
| 0 | 1 | none | 1 | 1 |
| 1 | 3 | j=0 (len 1) | 2 | 1 |
| 2 | 5 | j=0 (len 1), j=1 (len 2) | 3 | 1 |
| 3 | 4 | j=0 (len 1), j=1 (len 2); j=2 skipped since 5 > 4 | 3 | 1 |
| 4 | 7 | j=2 (len 3) sets count 1; j=3 (len 3) ties, count becomes 2 | 4 | 2 |
At i = 4, the replace case fires first. Predecessor j = 1 lifts the length to 3, and then j = 2 lifts it to 4 with count 1. Predecessor j = 3 then gives an equal length, so its count is added. The maximum length is 4, reached only at index 4, so the answer is 2. The two subsequences are 1, 3, 5, 7 and 1, 3, 4, 7.
The diagram shows what the count really measures. Draw an edge from j to i whenever length[i] = length[j] + 1. Then count[i] is the number of paths in that graph that end at i. The algorithm counts paths in a DAG (a directed acyclic graph) in topological order.
Edge Cases
All equal values. For [2, 2, 2, 2, 2], no element is strictly less than another, so every length[i] is 1 and every count[i] is 1. The maximum length is 1, and five indices reach it, so the answer is 5. If your function returns 1 here, it sums only one index.
Strictly decreasing input. For [5, 4, 3, 2, 1] the answer is also n, for the same reason.
Empty input. There are no subsequences of positive length. Returning 0 is the usual convention, and the guard clause handles it. Without it, max(length) raises ValueError.
Exponential counts. The count can grow exponentially with n. Look at [2, 1, 4, 3, 6, 5, ...]. Each adjacent pair adds one to the LIS length and offers two choices, so n elements give 2^(n/2) longest subsequences. Python integers have no fixed size, so they never overflow, but the numbers get large. In C++ or Java, or when a problem asks for the answer modulo 10^9 + 7, reduce at every addition: count[i] = (count[i] + count[j]) % MOD.
def count_pairs_example(k):
a = []
for p in range(k):
a += [2 * p + 2, 2 * p + 1]
return count_lis(a)
print([count_pairs_example(k) for k in range(1, 6)]) # [2, 4, 8, 16, 32]Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `count[i] = 1` in the "longer" branch | Undercounts whenever `j` itself had several chains | Copy `count[j]` |
| `count[i] += 1` in the "equal" branch | Undercounts in the same situations | Add `count[j]` |
| Returning `count[argmax(length)]` | Misses LIS that end at other indices; `[2,2,2]` returns 1 | Sum over every index with the best length |
| Using `<=` instead of `<` | Counts non-decreasing subsequences instead | Match the comparison to the problem |
| Counting with the tails array | Overwriting a tail throws away the counts for that length | Use the DP or a Fenwick tree that stores (length, count) pairs |
The last row matters if you already know the O(n log n) tails method. The tails array keeps only the smallest ending value for each length. When bisect_left overwrites tails[k], every other subsequence of length k + 1 is forgotten, including how many there were. Counting needs information the tails array throws away.
Checking Against Brute Force
On small inputs, compare against direct enumeration. Enumerating index combinations matches the index-counting convention exactly.
from itertools import combinations
import random
def count_lis_brute(a):
n = len(a)
for r in range(n, 0, -1):
c = sum(
1 for idx in combinations(range(n), r)
if all(a[idx[t]] < a[idx[t + 1]] for t in range(r - 1))
)
if c:
return c
return 0
for _ in range(500):
arr = [random.randint(0, 5) for _ in range(random.randint(0, 9))]
assert count_lis(arr) == count_lis_brute(arr), arr
print("all tests passed")The brute force goes through up to 2^n index sets, so only use it as a test oracle. Small value ranges such as 0 to 5 force many duplicates, which is where most counting bugs show up.
An O(n log n) Version
You can keep the O(n log n) running time if the data structure stores pairs (length, count) instead of lengths alone. Define a merge for two pairs: the pair with the larger length wins, and if the lengths are equal, the counts are added. This merge is associative and commutative, and a Fenwick tree only ever merges new values in, so a prefix query over ranks below a[i] returns the best length among smaller values together with its total count.
def count_lis_fenwick(a):
ranks = {v: i + 1 for i, v in enumerate(sorted(set(a)))}
m = len(ranks)
t_len = [0] * (m + 1)
t_cnt = [0] * (m + 1)
def merge(l1, c1, l2, c2):
if l1 > l2:
return l1, c1
if l2 > l1:
return l2, c2
return l1, c1 + c2
def query(i): # best (length, count) over ranks 1..i
l, c = 0, 0
while i > 0:
l, c = merge(l, c, t_len[i], t_cnt[i])
i -= i & -i
return l, c
def update(i, l, c):
while i <= m:
t_len[i], t_cnt[i] = merge(t_len[i], t_cnt[i], l, c)
i += i & -i
for x in a:
r = ranks[x]
l, c = query(r - 1)
if l == 0:
c = 1 # x starts a new subsequence by itself
update(r, l + 1, c)
return query(m)[1]
print(count_lis_fenwick([1, 3, 5, 4, 7])) # 2
print(count_lis_fenwick([2, 2, 2, 2, 2])) # 5Querying r - 1 instead of r keeps the order strict. An equal value already in the tree sits at rank r, so it is not included. The final query(m) merges every rank, which sums the counts of all indices that reach the maximum length. That is the same step as the final sum in the O(n^2) version. The next chapter explains the Fenwick tree mechanics.
Exercise
What does count_lis return for [1, 2, 4, 3, 5, 4, 7, 2]? Trace length and count for each index.
Show answer
The lengths are [1, 2, 3, 3, 4, 4, 5, 2] and the counts are [1, 1, 1, 1, 2, 1, 3, 1]. At index 4 (value 5), predecessors 4 and 3 both give length 4, so the count is 2. At index 5 (value 4), only 3 gives length 4, so the count is 1. At index 6 (value 7), indices 4 and 5 both give length 5, so the count is 2 + 1 = 3. The maximum length 5 appears only at index 6, so the answer is 3.
Exercise
Change count_lis so it counts longest non-decreasing subsequences. What does it return for [1, 2, 2, 3]?
Show answer
Change a[j] < a[i] to a[j] <= a[i]. Now 1, 2, 2, 3 using all four indices is valid, so the maximum length is 4 and exactly one index sequence reaches it. The function returns 1.
Exercise
count_lis([1, 2, 2, 3]) returns 2, but both subsequences spell 1, 2, 3. Describe a change that counts distinct value sequences instead.
Show answer
When several earlier indices hold the same value, count chains from only the latest such index. A later index sees every chain that an earlier equal value sees, plus possibly more, so the latest one covers them all. Inside the j loop, skip j if a later j' < i has a[j'] == a[j]. In the final sum, include only the last index of each value among those reaching the best length. For [1, 2, 2, 3], index 3 then takes chains only through index 2, which gives a count of 1.