Sub topic 12
A Fenwick Tree Formulation with Coordinate Compression
This chapter assumes you know the O(n^2) dynamic program from earlier chapters, where dp[i] is the length of the longest increasing subsequence ending at index i. It also assumes you have seen a Fenwick tree (binary indexed tree) used for prefix sums. Here the Fenwick tree keeps a prefix maximum instead of a prefix sum.
Rewriting the DP as a range query
The quadratic recurrence is:
dp[i] = 1 + max(dp[j] for j < i if a[j] < a[i]), or 1 if no such j exists.
The inner loop asks one question: among the elements already processed, which ones have a value below a[i], and what is the best dp among them? Suppose you index a table by value instead of position, storing at slot v the best dp of any processed element whose value is v. Then the question becomes "maximum over slots 1 .. a[i]-1". That is a prefix-maximum query, and a Fenwick tree answers it in O(log m), where m is the number of slots.
Processing left to right handles the j < i condition, because only earlier elements have been inserted. The value-indexed table handles the a[j] < a[i] condition.
Why coordinate compression is needed
Values can be negative, huge (up to 10^9), or floats, and a Fenwick tree needs small positive integer indices. Coordinate compression maps each distinct value to its rank in sorted order, starting at 1. Only relative order matters for LIS, so ranks give the same answer as the raw values.
| Value | 2 | 3 | 5 | 7 | 9 | 10 | 18 | 101 |
|---|---|---|---|---|---|---|---|---|
| Rank | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
The implementation
def lis_fenwick(a):
ranks = {v: i + 1 for i, v in enumerate(sorted(set(a)))}
m = len(ranks)
tree = [0] * (m + 1)
def query(i): # max dp over ranks 1..i
best = 0
while i > 0:
best = max(best, tree[i])
i -= i & -i
return best
def update(i, v):
while i <= m:
if tree[i] < v:
tree[i] = v
i += i & -i
ans = 0
for x in a:
r = ranks[x]
cur = query(r - 1) + 1
update(r, cur)
ans = max(ans, cur)
return ans
print(lis_fenwick([10, 9, 2, 5, 3, 7, 101, 18])) # 4Each element costs one query and one update, both O(log m). Sorting for compression costs O(n log n), so the whole algorithm is O(n log n) time and O(n) space.
Tracing the example
| x | rank r | query(r-1) | cur |
|---|---|---|---|
| 10 | 6 | 0 | 1 |
| 9 | 5 | 0 | 1 |
| 2 | 1 | 0 | 1 |
| 5 | 3 | 1 | 2 |
| 3 | 2 | 1 | 2 |
| 7 | 4 | 2 | 3 |
| 101 | 8 | 3 | 4 |
| 18 | 7 | 3 | 4 |
The maximum cur is 4, which matches the other methods.
When to prefer this over the tails array
The tails-array method from earlier chapters is shorter and also O(n log n). The Fenwick version is worth its extra code when the DP must combine more than one quantity per value. Two examples:
- Counting LIS in O(n log n): store a (length, count) pair per node and merge pairs by taking the longer length, summing counts on ties.
- Weighted LIS (maximize the sum of the chosen elements instead of the count): store the best sum and replace
+ 1with+ x.
The tails array relies on the fact that every element adds exactly 1 to the length, so it cannot handle either case.
The off-by-one in query(r - 1) is the most common bug. Writing query(r) lets equal values extend each other, which silently computes the non-decreasing variant.
Exercise
Modify lis_fenwick so it returns the length of the longest non-decreasing subsequence. What single change is needed, and what does it return for [1, 3, 3, 2, 3]?
Show answer
Change query(r - 1) to query(r), so elements with the same rank count as valid predecessors. For [1, 3, 3, 2, 3] it returns 4 (for example 1, 3, 3, 3).
Exercise
Adapt the algorithm to compute the maximum-sum strictly increasing subsequence of positive integers. What does it return for [1, 101, 2, 3, 100]?
Show answer
Replace cur = query(r - 1) + 1 with cur = query(r - 1) + x, keeping the same prefix-maximum tree. The best subsequence is 1, 2, 3, 100, so it returns 106.