Sub topic 5
The Tails Array: Smallest Ending Value per Length
The O(n^2) dynamic program asks, for every index, "how long is the best increasing subsequence that ends here?" It answers by comparing each element with every element before it. This chapter changes the question. For every possible length, it asks for the smallest value that can end an increasing subsequence of that length. The answers go in an array called tails. That array has a structure the dp array lacks: it is always sorted. The O(n log n) algorithm in the next chapter depends on that fact.
This chapter assumes you know the O(n^2) recurrence dp[i] = 1 + max(dp[j]) over j < i with a[j] < a[i]. You should be comfortable with loop invariants and short proofs by contradiction, and you should know what binary search needs from its input. To keep attention on the invariant, this chapter finds positions with a plain linear scan. Binary search replaces that scan in the next chapter.
From "Best Length per Index" to "Best Tail per Length"
The dp array keeps a lot of information that later elements never use. Suppose you have processed a prefix of the input and the next value is x. To extend some increasing subsequence of length L with x, you need only one thing: a subsequence of length L whose last element is less than x. Which subsequence it is, and where it ends, does not matter.
If several subsequences have length L, the one with the smallest last element is the best one to keep. Any x that can extend a subsequence of length L with tail t can also extend one with tail t' < t. A smaller tail accepts every value a larger tail accepts, plus some more.
This gives the definition:
tails[k]is the smallest value that ends any strictly increasing subsequence of lengthk + 1among the elements processed so far.
Indexing is 0-based, so tails[0] covers length 1, tails[1] covers length 2, and so on. The length of tails equals the LIS length of the prefix. A subsequence of length L exists exactly when slot L - 1 exists.
The Sorted Invariant
The key property is:
tails is strictly increasing: tails[0] < tails[1] < ... < tails[len-1].
Proof. Take any length L ≥ 2. Let S be an increasing subsequence of length L whose last element is tails[L-1], the smallest possible tail for that length. Drop the last element of S. What remains is an increasing subsequence of length L − 1, and its last element is strictly smaller than tails[L-1] because S is strictly increasing. The best tail for length L − 1 is at most that value, so tails[L-2] < tails[L-1].
The dp array has no such order. For [10, 9, 2, 5] it is [1, 1, 1, 2], and the values that end each length are scattered across the input. The tails array for the same input is [2, 5], which is sorted.
The Update Rule
Every new element x changes tails in exactly one place:
- Find the first index
kwithtails[k] >= x. - If no such index exists, append
x. The LIS just grew by one. - Otherwise, set
tails[k] = x.
The first index with a value >= x is a "lower bound" search. That is why Python's bisect_left fits in the next chapter.
Why exactly one slot changes
Let k be the first index with tails[k] >= x. Then tails[k-1] < x if k > 0. Consider each length that might improve:
- Slot
k. The subsequence that ends attails[k-1]has lengthk, andxis larger than its tail, so appendingxgives a subsequence of lengthk + 1that ends atx. Sincex <= tails[k],xis at least as good as the old tail. Ifk == 0,xalone is a subsequence of length 1. - Slots before
k. A new subsequence of lengthj + 1that ends atxwould putxin slotj. Buttails[j] < xfor everyj < k, so the slot already holds something smaller. Nothing changes. - Slots after
k. To end a subsequence of lengthj + 1 > k + 1atx, you need a subsequence of lengthjwhose tail is belowx. Its tail is at leasttails[j-1] >= tails[k] >= x, so none exists.
The invariant also survives the update. After the write, tails[k-1] < x <= tails[k] < tails[k+1], so the new x lies strictly between its neighbours.
A Worked Trace
Here is the rule applied to [10, 9, 2, 5, 3, 7, 101, 18]:
| Step | x | First k with tails[k] >= x | Action | tails after |
|---|---|---|---|---|
| 1 | 10 | none | append | [10] |
| 2 | 9 | 0 (10) | replace | [9] |
| 3 | 2 | 0 (9) | replace | [2] |
| 4 | 5 | none | append | [2, 5] |
| 5 | 3 | 1 (5) | replace | [2, 3] |
| 6 | 7 | none | append | [2, 3, 7] |
| 7 | 101 | none | append | [2, 3, 7, 101] |
| 8 | 18 | 3 (101) | replace | [2, 3, 7, 18] |
The final length is 4, matching the quadratic DP. Look at step 5. Replacing 5 with 3 does not lengthen anything, but it lowers the bar for length 2. That is why 7 can later extend to length 3 using either 2, 5 or 2, 3. The replacement at step 8 shows that a later value like 19 could extend to length 5 through ..., 18, which 101 would block.
Implementation with a Linear Scan
The code below applies the rule with a linear scan and checks the invariant after every step. It also compares tails with a brute-force reading of the definition on random inputs. In that reading, the smallest tail for length L is the minimum a[i] over indices with dp[i] >= L. Any subsequence of length dp[i] that ends at i can be shortened from the front to any length L ≤ dp[i].
import random
def tails_by_update(a):
tails = []
for x in a:
k = 0
while k < len(tails) and tails[k] < x: # first k with tails[k] >= x
k += 1
if k == len(tails):
tails.append(x)
else:
tails[k] = x
assert all(tails[i] < tails[i + 1] for i in range(len(tails) - 1))
return tails
def tails_by_definition(a):
n = len(a)
if n == 0:
return []
dp = [1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i]:
dp[i] = max(dp[i], dp[j] + 1)
return [min(a[i] for i in range(n) if dp[i] >= L)
for L in range(1, max(dp) + 1)]
print(tails_by_update([10, 9, 2, 5, 3, 7, 101, 18])) # [2, 3, 7, 18]
random.seed(0)
for _ in range(1000):
a = [random.randint(0, 9) for _ in range(random.randint(0, 12))]
for p in range(len(a) + 1):
assert tails_by_update(a[:p]) == tails_by_definition(a[:p])
print("tails matches its definition on every prefix")The random inputs use values from 0 to 9, so they contain many duplicates. That exercises the >= condition. The scan makes each step O(L), so the worst case is still O(n^2). The scan only ever looks for a lower bound in a sorted array, and the next chapter replaces it with binary search to get O(log n) per step.
Common Mistakes
Treating tails as an actual subsequence
The tails array is not, in general, an increasing subsequence of the input. In the trace above, the final [2, 3, 7, 18] happens to be valid, which makes this mistake easy to miss. Try [3, 4, 5, 1]:
| x | tails after |
|---|---|
| 3 | [3] |
| 4 | [3, 4] |
| 5 | [3, 4, 5] |
| 1 | [1, 4, 5] |
The length 3 is correct, but [1, 4, 5] is not a subsequence: the 1 comes after the 5 in the input. Each slot belongs to a different candidate subsequence. Slot 0 now describes the one-element subsequence [1], while slots 1 and 2 still describe [3, 4] and [3, 4, 5]. A later chapter recovers a real subsequence by recording indices and predecessor links.
Thinking replacement can shorten the answer
Replacing a value never removes a length. Slot k still exists after the write. It now holds a smaller tail, which only makes extending easier. len(tails) never decreases.
Picking the wrong slot
Writing x anywhere other than the first slot with tails[k] >= x breaks the invariant or loses information. Writing too far left overwrites a smaller tail with a larger one. Writing too far right puts x after a tail it cannot extend, so the array is no longer sorted, and the binary search in the next chapter would give wrong answers.
Complexity and What Is Kept
| Quantity | dp array (previous chapter) | tails array (this chapter) |
|---|---|---|
| Entries | one per input index (n) | one per length (at most LIS length) |
| Ordered? | no | strictly increasing |
| Work per element | O(i) comparisons | O(L) scan, O(log L) with binary search |
| Recovers a subsequence directly? | yes, with parent pointers | no, needs extra index bookkeeping |
The space saving matters when the LIS is short compared with n. The bigger gain is the order. Because tails is sorted, the search for the right slot can use binary search.
Exercise
Run the update rule on [4, 10, 4, 3, 8, 9]. Give tails after each element, and state the final LIS length.
Show answer
4 gives [4]. 10 gives [4, 10]. The second 4 finds tails[0] = 4 >= 4 and replaces it, leaving [4, 10]. 3 replaces slot 0, giving [3, 10]. 8 replaces slot 1 (10 >= 8), giving [3, 8]. 9 is appended, giving [3, 8, 9]. The LIS length is 3, for example 4, 8, 9 or 3, 8, 9.
Exercise
Someone changes the scan condition from tails[k] < x to tails[k] <= x, so the code finds the first k with tails[k] > x. What does the function now compute on [2, 2, 2]? Is the result correct for strictly increasing subsequences?
Show answer
Each 2 now skips past any equal 2, so the array grows to [2, 2, 2] and the function returns 3. That is the longest non-decreasing subsequence. For strictly increasing subsequences the correct answer is 1, so the result is wrong. The array also stops being strictly increasing.
Exercise
The proof of the sorted invariant drops the last element of a length-L subsequence. Why does that show tails[L-2] < tails[L-1] and not just tails[L-2] <= tails[L-1]?
Show answer
The subsequence is strictly increasing, so its second-to-last element is strictly less than its last element, tails[L-1]. Removing the last element leaves a length L-1 subsequence with that smaller tail, and tails[L-2] is at most that tail. So tails[L-2] is strictly less than tails[L-1].
Exercise
After processing [3, 4, 5, 1], tails is [1, 4, 5]. The next element is 6. Which slot changes, and is the new LIS length correct even though [1, 4, 5] is not a real subsequence?
Show answer
No slot holds a value >= 6, so 6 is appended, giving [1, 4, 5, 6] and length 4. The length is correct because slot 2 still describes the real subsequence 3, 4, 5, and 6 extends it to 3, 4, 5, 6. Each slot is valid for its own length, even when the slots together do not form one subsequence.