Sub topic 13
Patience Sorting, Piles, and Dilworth's Theorem
This chapter assumes you know the O(n log n) tails-array algorithm and the bisect_left vs bisect_right distinction from earlier chapters. You should also be comfortable reading Python and following a short proof by contradiction. No prior knowledge of order theory is needed. The one definition we use is introduced below.
The tails array can look like a clever trick. It is actually a card game called patience sorting, which mathematicians studied long before the algorithm was written down. Seen as a game, the algorithm becomes easier to remember. It also explains why the pile count equals the LIS length, and it connects LIS to a classical result about partially ordered sets, Dilworth's theorem.
The Card Game
You deal the sequence one card at a time, left to right. Each card goes onto a pile, using one rule:
- Look at the top card of each pile, from left to right.
- Put the new card on the leftmost pile whose top card is greater than or equal to the new card.
- If no such pile exists, start a new pile on the right.
That is the whole game. The tops of the piles, read left to right, are exactly the tails array. Step 2 is the bisect_left search for the first top that is >= x.
Here is the deal for [10, 9, 2, 5, 3, 7, 101, 18]:
| Card | Leftmost top ≥ card | Action | Pile tops after |
|---|---|---|---|
| 10 | none | new pile 1 | 10 |
| 9 | 10 (pile 1) | place on pile 1 | 9 |
| 2 | 9 (pile 1) | place on pile 1 | 2 |
| 5 | none | new pile 2 | 2, 5 |
| 3 | 5 (pile 2) | place on pile 2 | 2, 3 |
| 7 | none | new pile 3 | 2, 3, 7 |
| 101 | none | new pile 4 | 2, 3, 7, 101 |
| 18 | 101 (pile 4) | place on pile 4 | 2, 3, 7, 18 |
The final piles, listed bottom to top, are [10, 9, 2], [5, 3], [7], [101, 18]. There are four piles, and the LIS length is 4.
Implementing the Piles
The code below keeps the full piles, not only their tops, so you can inspect them. Each card also stores a back pointer to the top of the pile on its left at the moment it was dealt. This is the same parent-pointer idea used for O(n log n) reconstruction.
from bisect import bisect_left
def deal_piles(a):
"""Play patience with the strict rule.
Returns (piles, parent), where piles[k] lists indices bottom to top and
parent[i] is the index of the card on pile k-1's top when a[i] was dealt.
"""
piles = [] # piles[k] is a list of indices into a
tops = [] # tops[k] == a[piles[k][-1]], kept strictly increasing
parent = [-1] * len(a)
for i, x in enumerate(a):
k = bisect_left(tops, x) # leftmost top >= x
if k > 0:
parent[i] = piles[k - 1][-1]
if k == len(piles):
piles.append([i])
tops.append(x)
else:
piles[k].append(i)
tops[k] = x
return piles, parent
def lis_from_piles(a):
piles, parent = deal_piles(a)
if not piles:
return []
i = piles[-1][-1] # any card in the last pile works
seq = []
while i != -1:
seq.append(a[i])
i = parent[i]
return seq[::-1]
a = [10, 9, 2, 5, 3, 7, 101, 18]
piles, _ = deal_piles(a)
print([[a[i] for i in p] for p in piles]) # [[10, 9, 2], [5, 3], [7], [101, 18]]
print(lis_from_piles(a)) # [2, 3, 7, 18]Why Pile Count Equals LIS Length
The proof has two halves. Each half shows one inequality.
Lower bound: any increasing subsequence uses at most one card per pile
A card is placed only on a top that is greater than or equal to it. So within a pile, reading bottom to top (which is also deal order), the values never increase. Each pile is a non-increasing subsequence of the input. A strictly increasing subsequence cannot contain two cards from the same pile, because the later card would be less than or equal to the earlier one. With p piles, every increasing subsequence has length at most p.
Upper bound: the back pointers build an increasing subsequence of length p
When card a[i] lands on pile k, the top of pile k−1 is strictly smaller than a[i]. If it were not, bisect_left would have picked pile k−1. That top card was also dealt earlier. So each back pointer leads to an earlier, smaller card exactly one pile to the left. Starting from any card in the last pile and following pointers visits one card in each pile and produces a strictly increasing subsequence of length p.
Together, the two bounds give LIS length = p. The argument also shows something stronger. The piles split the input into p non-increasing subsequences, and nothing can do it with fewer, since the LIS needs p different groups. This is a min-max equality, and min-max equalities are what Dilworth's theorem is about.
Dilworth's Theorem and Its Dual
A partial order is a relation ≺ that is irreflexive and transitive. Some pairs of elements may be incomparable. A chain is a set of pairwise comparable elements. An antichain is a set of pairwise incomparable elements.
Two classical theorems apply to any finite partial order:
- Dilworth's theorem: the size of the largest antichain equals the minimum number of chains needed to cover all elements.
- Mirsky's theorem (the dual): the length of the longest chain equals the minimum number of antichains needed to cover all elements.
Turn a sequence into a partial order on its indices: i ≺ j when i < j and a[i] < a[j]. Then the terms translate directly:
| Order-theory term | Meaning for the sequence |
|---|---|
| Chain | Strictly increasing subsequence |
| Antichain | Subsequence where every earlier value is ≥ every later one, i.e. non-increasing |
| Longest chain | LIS |
| Minimum antichain cover | Fewest non-increasing subsequences covering the sequence |
Mirsky's theorem therefore says: LIS length = minimum number of non-increasing subsequences that partition the sequence. Patience sorting proves this constructively. Its piles are such a partition, and the greedy leftmost rule always reaches the minimum.
Dilworth's theorem itself gives the mirror statement: the longest non-increasing subsequence has the same length as the fewest strictly increasing subsequences that cover the sequence. You can compute that cover with the same game. Change the rule to "leftmost top strictly greater than the card" (bisect_right) and run it on the negated values.
Strictness and duplicates
The pile rule must match the comparison in the partial order. Under the strict rule (bisect_left), a card equal to a top goes onto that pile, because equal values cannot both appear in a strictly increasing subsequence. Piles are then non-increasing. Under the non-decreasing rule (bisect_right), an equal card starts a new pile or goes further right, and piles become strictly decreasing.
| Goal | Search | Pile contents | Pile count equals |
|---|---|---|---|
| Strictly increasing LIS | `bisect_left` | non-increasing | longest strictly increasing |
| Non-decreasing LIS | `bisect_right` | strictly decreasing | longest non-decreasing |
Using the wrong bound is the usual bug. Each pile is still a valid antichain for some order, but for the other order, so the count answers a different question.
Patience Sorting as a Sort
The game was named because it also sorts. Each pile is non-increasing from bottom to top, so reading it from the top down gives a non-decreasing run. Merging all runs with a heap produces sorted output.
import heapq
import random
def patience_sort(a):
piles, _ = deal_piles(a)
runs = [[a[i] for i in reversed(p)] for p in piles] # each run is ascending
return list(heapq.merge(*runs))
def lis_quadratic(a):
dp = [1] * len(a)
for i in range(len(a)):
for j in range(i):
if a[j] < a[i]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp, default=0)
random.seed(1)
for _ in range(2000):
a = [random.randint(0, 9) for _ in range(random.randint(0, 12))]
piles, _ = deal_piles(a)
assert patience_sort(a) == sorted(a)
assert len(piles) == lis_quadratic(a)
for p in piles: # every pile is non-increasing
vals = [a[i] for i in p]
assert all(x >= y for x, y in zip(vals, vals[1:]))
seq = lis_from_piles(a)
assert len(seq) == len(piles)
assert all(x < y for x, y in zip(seq, seq[1:]))
print("all checks passed")Dealing costs O(n log p) and the merge costs O(n log p), where p is the LIS length. On nearly sorted input p is close to n, and the sort is no faster than a heap sort. On input made of a few interleaved decreasing runs, p is small and the sort runs close to linear time. The sort has practical value only in such special cases. For LIS work, its value is the proof.
Erdős–Szekeres as a Corollary
Combine the two theorems. Suppose a sequence of length n has LIS length r. Then it splits into r non-increasing piles, so some pile holds at least ⌈n / r⌉ cards. That pile is a non-increasing subsequence. In particular:
- (LIS length) × (longest non-increasing length) ≥ n.
- Any sequence of more than r·s distinct values has an increasing subsequence of length r+1 or a decreasing one of length s+1. This is the Erdős–Szekeres theorem.
For example, any arrangement of 10 distinct numbers has a monotone run of length 4, since 3 × 3 = 9 < 10. The bound is tight: [7, 8, 9, 4, 5, 6, 1, 2, 3] has nine values, and its longest increasing and longest decreasing subsequences both have length 3.
Exercise
Deal [4, 4, 4, 4] with the strict rule (bisectleft) and with the non-decreasing rule (bisectright). How many piles does each produce, and what does each count mean in terms of subsequences?
Show answer
With bisectleft, each 4 finds the existing top 4 (which is >= 4) and lands on it, giving 1 pile: the longest strictly increasing subsequence has length 1, and the whole sequence is a single non-increasing subsequence. With bisectright, no top is strictly greater than 4, so each card starts a new pile, giving 4 piles: the longest non-decreasing subsequence has length 4, and the sequence needs 4 strictly decreasing subsequences (single elements) to cover it.
Exercise
Using Dilworth's theorem, what is the minimum number of strictly increasing subsequences needed to cover [5, 1, 4, 2, 3]? Give the number and one cover that achieves it.
Show answer
The longest non-increasing subsequence has length 2 (for example 5, 1 or 4, 2), so by Dilworth's theorem the minimum is 2. One cover is [1, 2, 3] and [5] plus [4] merged appropriately: [1, 2, 3] and [4] alone would leave 5, so use [5] can't join anything after it except smaller values. A valid 2-cover is [1, 2, 3] and [5]... which misses 4, so the correct cover is [1, 4] and [5], which misses 2 and 3. Check carefully: 5 must start a chain and nothing after it is larger, so 5 is alone in its chain; the other chain must then be 1, 4, 2, 3, which is not increasing. So the minimum is 3, and the longest non-increasing subsequence is in fact 5, 4, 3 (or 5, 4, 2), which has length 3. A minimum cover is [5], [1, 4], [2, 3].
Exercise
Why does following back pointers from any card in the last pile, not only its top, still give a longest increasing subsequence?
Show answer
Every card in pile k recorded a pointer to the card then on top of pile k-1, which was dealt earlier and is strictly smaller. That holds for every card, whenever it was placed. So any chain of pointers that starts in the last pile p visits piles p, p-1, ..., 1 with strictly decreasing values and indices, which read forward is a strictly increasing subsequence of length p.