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 strictly increasing subsequence ending at index i. It also assumes you are comfortable with Python and Big-O notation, and that you have met a Fenwick tree (binary indexed tree) at least once, even if only for prefix sums.
The tails-array method already runs in O(n log n), so a second O(n log n) method needs a reason to exist. The Fenwick formulation keeps the dp[i] values explicit. That makes it easy to change what each element contributes. You can maximize a sum of weights, count optimal subsequences, or carry extra data along, and the tails array cannot do any of these without awkward changes.
Rephrasing the Recurrence as a Range Query
The quadratic recurrence is:
dp[i] = 1 + max(dp[j])over allj < iwitha[j] < a[i], ordp[i] = 1if no suchjexists.
The inner loop scans every earlier index. Look at the two conditions separately:
j < iis a condition on position.a[j] < a[i]is a condition on value.
If you process the array left to right, the first condition is automatic: everything you have already processed comes earlier. Only the value condition is left. Suppose you keep a structure indexed by value, where slot v holds the best dp seen so far for elements equal to v. Then max(dp[j]) becomes "the maximum over all slots with value less than a[i]." That is a prefix maximum query over value space.
A Fenwick tree answers prefix maximum queries in O(log m) and applies point updates in O(log m), where m is the number of slots. There is one obstacle: values can be huge, negative, or non-integer, and a Fenwick tree needs small positive integer indices.
Coordinate Compression
Coordinate compression replaces each value with its rank among the distinct values. The smallest distinct value gets rank 1, the next gets rank 2, and so on. Ranks keep every comparison intact: a[j] < a[i] holds exactly when rank(a[j]) < rank(a[i]). Equal values get equal ranks.
For the running example [10, 9, 2, 5, 3, 7, 101, 18]:
| Value | 2 | 3 | 5 | 7 | 9 | 10 | 18 | 101 |
|---|---|---|---|---|---|---|---|---|
| Rank | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
Compression costs O(n log n) for the sort and leaves m ≤ n slots. The Fenwick tree then uses O(m) memory no matter how large the original values are.
The Algorithm
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])) # 4Node tree[i] covers ranks i - lowbit(i) + 1 through i, where lowbit(i) = i & -i. A query walks downward and strips the lowest set bit each step, so it visits disjoint ranges that together cover 1..i. An update walks upward and adds the lowest set bit each step, so it reaches every node whose range contains i.
The query uses r - 1 and not r. That excludes elements with the same value and enforces strictness.
Tracing the Example
Each row shows the element, its rank, the prefix query, and the resulting dp value. That value is the same one the quadratic DP computes.
| x | r | query(r − 1) | dp = cur | Nodes touched by update |
|---|---|---|---|---|
| 10 | 6 | query(5) = 0 | 1 | tree[6], tree[8] |
| 9 | 5 | query(4) = 0 | 1 | tree[5], tree[6], tree[8] |
| 2 | 1 | query(0) = 0 | 1 | tree[1], tree[2], tree[4], tree[8] |
| 5 | 3 | query(2) = 1 | 2 | tree[3], tree[4], tree[8] |
| 3 | 2 | query(1) = 1 | 2 | tree[2], tree[4], tree[8] |
| 7 | 4 | query(3) = 2 | 3 | tree[4], tree[8] |
| 101 | 8 | query(7) = 3 | 4 | tree[8] |
| 18 | 7 | query(6) = 3 | 4 | tree[7], tree[8] |
Take x = 18 as a check. query(6) reads tree[6] (ranks 5–6, best 1) and then tree[4] (ranks 1–4, best 3), so the result is 3. The 101 sitting at rank 8 is correctly ignored because 101 > 18.
Why a Max Fenwick Tree Is Safe Here
A Fenwick tree for sums supports arbitrary point changes because subtraction undoes addition. Maximum has no inverse. If a slot's value ever had to go down, the nodes above it would keep the stale larger value, and you could not repair them without rebuilding.
LIS never needs a decrease. A slot's value only matters as "the best dp ending at this value so far," and that number can only grow as more elements arrive. Each update is tree[i] = max(tree[i], v), which is monotone. So the structure stays correct.
Common Errors
- Querying
rinstead ofr - 1. This lets equal values chain, so you compute the longest non-decreasing subsequence. It is a bug when you wanted strict, and it is exactly the fix when you want non-strict. - Forgetting compression. Indexing the tree by raw values crashes on negatives and zero, and it wastes memory on large values.
- Zero-based ranks. With rank 0,
i & -iis 0, soupdate(0, v)loops forever. Ranks must start at 1. - Updating before querying. If you write
curinto the tree before computing it, or query after the update, an element can see itself. Always query first. - Returning
query(m)but forgetting the empty case. Bothquery(m)and the runninganswork, and both return 0 for an empty list, becausem = 0and the loop never runs.
The Non-Decreasing Variant
Changing one character switches the problem:
def longest_non_decreasing_fenwick(a):
ranks = {v: i + 1 for i, v in enumerate(sorted(set(a)))}
m = len(ranks)
tree = [0] * (m + 1)
def query(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 # include equal values
update(r, cur)
ans = max(ans, cur)
return ans
print(longest_non_decreasing_fenwick([1, 3, 3, 2, 3])) # 4This mirrors the bisect_left vs bisect_right choice in the tails method. Here the choice shows up as the query bound.
Carrying More Than a Length: Counting
The Fenwick version gets more useful once each slot stores a pair (length, count). Combining two pairs keeps the longer length. When the lengths tie, it adds the counts. Every query covers disjoint rank ranges, so adding counts never double-counts a subsequence. This counts all longest increasing subsequences in O(n log n). The counting chapter's DP solved the same problem in O(n^2).
def count_lis_fenwick(a):
ranks = {v: i + 1 for i, v in enumerate(sorted(set(a)))}
m = len(ranks)
tree = [(0, 0)] * (m + 1) # (best length, number of ways)
def combine(p, q):
if p[0] != q[0]:
return p if p[0] > q[0] else q
return (p[0], p[1] + q[1])
def query(i):
res = (0, 0)
while i > 0:
res = combine(res, tree[i])
i -= i & -i
return res
def update(i, val):
while i <= m:
tree[i] = combine(tree[i], val)
i += i & -i
for x in a:
r = ranks[x]
length, ways = query(r - 1)
cur = (length + 1, ways) if length > 0 else (1, 1)
update(r, cur)
return query(m)[1]
print(count_lis_fenwick([1, 3, 5, 4, 7])) # 2The (1, 1) case covers an element with no smaller predecessor. It starts exactly one new subsequence of length 1.
Counting updates are not pure maxima, because equal lengths add their counts together. They are still safe, because a slot never needs to give back length or ways it has already recorded.
Choosing Between the Methods
| Method | Time | Extra space | Handles weights or counts | Needs compression |
|---|---|---|---|---|
| Quadratic DP | O(n^2) | O(n) | Yes, directly | No |
| Tails array + binary search | O(n log n) | O(n) | No, not naturally | No |
| Fenwick tree over ranks | O(n log n) | O(n) | Yes, by changing the combine | Yes |
Use the tails array when you only need the length or one witness subsequence. It is shorter and has smaller constants. Use the Fenwick tree when each element adds something other than 1, when you need counts, or when you need to aggregate over "all earlier elements with smaller value" in some other way. The tails array cannot express those because it throws away the per-element dp values.
Exercise
Modify lis_fenwick to compute the maximum sum of a strictly increasing subsequence, where each element contributes its own value (assume all values are positive). What result do you get for [1, 101, 2, 3, 100, 4, 5]?
Show answer
Replace cur = query(r - 1) + 1 with cur = query(r - 1) + x. The tree still stores prefix maxima and updates stay monotone, so nothing else changes. For [1, 101, 2, 3, 100, 4, 5] the answer is 106, from 1, 2, 3, 100.
Exercise
Why does the update loop in lis_fenwick never terminate if a rank of 0 is passed to update?
Show answer
For i = 0, i & -i equals 0, so i += i & -i leaves i at 0 and the condition i <= m stays true forever. Fenwick indices must start at 1, which is why compression assigns ranks starting from 1.
Exercise
In the trace for [10, 9, 2, 5, 3, 7, 101, 18], which tree nodes does query(6) read when x = 18, and which ranks does each one cover?
Show answer
It reads tree[6], which covers ranks 5–6 (values 9 and 10), and then tree[4], which covers ranks 1–4 (values 2, 3, 5, 7). The maxima are 1 and 3, so the query returns 3 and dp for 18 is 4.