Longest Increasing Subsequence in O(n log n)
Patience sorting, binary search and the Erdős–Szekeres theorem.
Deal a shuffled deck into piles by one rule: each card goes on the leftmost pile whose top card is at least as high, or starts a new pile on the right. The number of piles is the length of a longest increasing subsequence of the deck. Behind this card game sit an algorithm with a matching lower bound, a 1935 theorem of Erdős and Szekeres, and the fact that a random permutation of numbers has a longest increasing subsequence of length close to .
What you’ll learn
- Prove the tails invariant of patience sorting, derive the bound, and recover an LIS with predecessor indices.
- Adapt the method to non-decreasing subsequences, and prove that the LIS length equals the fewest non-increasing subsequences that partition the sequence.
- Prove the Erdős–Szekeres theorem by pigeonhole and show that it is tight.
- State the law for random permutations with its Tracy–Widom fluctuations, and the comparison lower bound for computing the LIS.
The tails invariant
Sorted. Take an increasing subsequence of length ending at . Its next-to-last element is smaller than and ends a subsequence of length , so
Where fits. An increasing subsequence of length can end at exactly when some subsequence of length ends below , that is when . Since the tails are sorted, the longest such is , with :
Only changes. For , , so cannot lower . For , ends no subsequence that long. And , so becomes the new (or the new last tail when ). Each step is one binary search over a sorted array:
from bisect import bisect_left
def lis(a):
"""One longest strictly increasing subsequence of a, in O(n log n)."""
tail_val, tail_idx = [], [] # the tails, and where in a each one sits
prev = [-1] * len(a) # prev[i]: predecessor of a[i] in its subsequence
for i, x in enumerate(a):
k = bisect_left(tail_val, x)
if k > 0:
prev[i] = tail_idx[k - 1] # extend a best subsequence of length k
if k == len(tail_val):
tail_val.append(x); tail_idx.append(i)
else:
tail_val[k], tail_idx[k] = x, i
out, i = [], (tail_idx[-1] if a else -1)
while i != -1:
out.append(a[i]); i = prev[i]
return out[::-1]
print(lis([31, 12, 47, 25, 39, 18, 52, 44, 60, 36])) # [12, 25, 39, 44, 60]Each element records the index of the tail it extended, the element sitting at at that moment; following these pointers back from the last tail spells out an LIS. Checked against brute force on thousands of random sequences. For non-decreasing subsequences, replace bisect_left by bisect_right.
Piles: the dual of an increasing subsequence
In the card game, a card goes on the leftmost pile whose top is the card, so every pile, read in the order cards were placed, is non-increasing. The pile tops are exactly the tails. That gives a second meaning to the LIS length.
Patience sorting deals . Which piles does it build?
- , , , : four piles, the LIS length
- , , , : four piles
- , , , , : five piles
- , , , , , , , : one pile per card
Show the answer
A. , , , : four piles, the LIS length
3 starts a pile; 1 goes on the 3; 4 starts a pile; the second 1 goes on the first pile (its top, 1, is ); 5 and 9 start piles; 2 goes on the 4 (the leftmost top ); 6 goes on the 9. Four non-increasing piles, matching an LIS such as , and no partition into three is possible.
The same structure counts things. Storing, for each length, the number of subsequences ending at each tail (or using a Fenwick tree over values) counts all longest increasing subsequences in ; negating the values turns every statement into its decreasing mirror image.
The Erdős–Szekeres theorem
Label each element with the pair : the lengths of a longest increasing and a longest decreasing subsequence ending at . These are the entries of the two DP tables, one per direction.
The labels are distinct. For : if , every increasing subsequence ending at extends by , so ; otherwise , since the values are distinct, and by the same argument.
If every and every , only labels exist, fewer than the elements: impossible, by the pigeonhole principle. Tightness: write blocks of values, each block decreasing and every block above the previous one, such as . An increasing subsequence takes at most one element per block, and a decreasing one stays inside a block.
The duality of the previous step gives a second proof in one line. For distinct values, the sequence splits into LIS decreasing parts, each of length at most LDS, so , and in particular .
What is the smallest such that every sequence of distinct numbers has a monotone (increasing or decreasing) subsequence of length 5?
Show the answer
17
With the theorem needs more than elements, so 17 suffice, and the tight construction with four decreasing blocks of four shows that 16 do not.
Random permutations and lower bounds
How long is the LIS of a random permutation? Ulam asked in the 1960s. Hammersley (1972) proved that converges to a constant, and Logan and Shepp and, independently, Vershik and Kerov (both 1977) showed that the constant is 2:
The mean of is about , so . A simulation agrees: 200 random permutations of elements had a mean LIS of about 192, against the prediction .
Key takeaways
- The tails array stores, for each length, the smallest possible last element of an increasing subsequence; it stays sorted, one binary search updates it, and its length is the LIS: time.
bisect_leftgives strict increase,bisect_rightnon-decreasing. - Predecessor indices, recorded when an element lands at position (pointing at the element in ), recover an actual LIS; the tails array itself is not one.
- Patience piles are non-increasing, and their number equals the LIS length: the fewest non-increasing subsequences covering a sequence is its LIS (Mirsky, the dual of Dilworth).
- Erdős–Szekeres: more than distinct numbers force an increasing subsequence of length or a decreasing one of length , by pigeonhole on the two DP tables. A random permutation has an LIS of about with Tracy–Widom fluctuations of order , and comparisons are optimal (Fredman, 1975).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
The tails are and the next element is 5. What happens in the strict and in the non-decreasing version?
- Strict: 5 replaces the 9; non-decreasing: 5 is appended
- Strict: nothing changes (5 replaces the equal tail 5); non-decreasing: 5 replaces the 9, giving
- Both append 5, giving
- Strict: 5 replaces the 2; non-decreasing: nothing changes
Show the answer
B. Strict: nothing changes (5 replaces the equal tail 5); non-decreasing: 5 replaces the 9, giving
bisect_left finds index 1, the first tail : a strictly increasing subsequence can end at 5 only with length 2, whose best tail is already 5. bisect_right finds index 2, the first tail : with repeats allowed, has length 3 and a smaller tail than 9.
What is the fewest non-increasing subsequences into which a sequence can be partitioned?
- The length of a longest non-increasing subsequence
- The length of a longest strictly increasing subsequence
- The number of distinct values
- Always 2
Show the answer
B. The length of a longest strictly increasing subsequence
A strictly increasing subsequence meets each non-increasing part at most once, so at least LIS parts are needed, and patience sorting's piles achieve exactly that many (Mirsky's theorem, the dual of Dilworth's).
Every permutation of is guaranteed to contain a monotone subsequence of length at least…
- 10
- 11
- 51
- 7, about
Show the answer
B. 11
, so with the theorem gives an increasing or a decreasing subsequence of length 11. Ten decreasing blocks of ten values show that 100 numbers can avoid length 11, and similar blocks show that 101 numbers can avoid length 12, so 11 is the exact guarantee.
About how long is a longest increasing subsequence of a uniformly random permutation of numbers?
- About 20
- About 2,000
- About 20,000
- About 500,000
Show the answer
B. About 2,000
, with fluctuations of order . The growth is like : not logarithmic, and far from a constant fraction of .
Further reading
- D. Aldous & P. Diaconis, "Longest increasing subsequences: from patience sorting to the Baik–Deift–Johansson theorem," Bulletin of the AMS 36(4) (1999), 413–432.
- P. Erdős & G. Szekeres, "A combinatorial problem in geometry," Compositio Mathematica 2 (1935), 463–470.
- J. Baik, P. Deift & K. Johansson, "On the distribution of the length of the longest increasing subsequence of random permutations," Journal of the AMS 12(4) (1999), 1119–1178.
- M. L. Fredman, "On computing the length of longest increasing subsequences," Discrete Mathematics 11(1) (1975), 29–35.
- L. Mirsky, "A dual of Dilworth's decomposition theorem," American Mathematical Monthly 78 (1971), 876–877.