Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 O(nlog⁡n)O(n \log n) algorithm with a matching lower bound, a 1935 theorem of Erdős and Szekeres, and the fact that a random permutation of nn numbers has a longest increasing subsequence of length close to 2n2\sqrt n.

What you’ll learn

  • Prove the tails invariant of patience sorting, derive the O(nlog⁡n)O(n \log n) 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 2n2\sqrt n law for random permutations with its Tracy–Widom fluctuations, and the comparison lower bound for computing the LIS.

The tails invariant

DerivationProof
  1. Tk ≤ (next-to-last element) < Tk+1T_k\ \le\ \text{(next-to-last element)}\ <\ T_{k+1}

    Sorted. Take an increasing subsequence of length k+2k + 2 ending at Tk+1T_{k+1}. Its next-to-last element is smaller than Tk+1T_{k+1} and ends a subsequence of length k+1k + 1, so

  2. x ends a subsequence of length k+1, and none longerx \text{ ends a subsequence of length } k + 1, \text{ and none longer}

    Where xx fits. An increasing subsequence of length j+1≥2j + 1 \ge 2 can end at xx exactly when some subsequence of length jj ends below xx, that is when Tj−1<xT_{j-1} < x. Since the tails are sorted, the longest such j+1j + 1 is k+1k + 1, with k=#{ t:Tt<x }k = \#\{\,t : T_t < x\,\}:

  3. T(n)=∑i=1nO(log⁡i)=O(nlog⁡n)T(n) = \sum_{i=1}^{n} O(\log i) = O(n \log n)

    Only TkT_k changes. For t<kt < k, Tt<xT_t < x, so xx cannot lower TtT_t. For t>kt > k, xx ends no subsequence that long. And Tk≥xT_k \ge x, so xx becomes the new TkT_k (or the new last tail when k=Lk = L). Each step is one binary search over a sorted array:

python
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 Tk−1T_{k-1} 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 ≥\ge 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.

Check your understanding

Patience sorting deals [3,1,4,1,5,9,2,6][3, 1, 4, 1, 5, 9, 2, 6]. Which piles does it build?

  1. [3,1,1][3, 1, 1], [4,2][4, 2], [5][5], [9,6][9, 6]: four piles, the LIS length
  2. [3,1][3, 1], [4,1][4, 1], [5,2][5, 2], [9,6][9, 6]: four piles
  3. [3,1,1][3, 1, 1], [4,2][4, 2], [5][5], [9][9], [6][6]: five piles
  4. [3][3], [1][1], [4][4], [1][1], [5][5], [9][9], [2][2], [6][6]: one pile per card
Show the answer

A. [3,1,1][3, 1, 1], [4,2][4, 2], [5][5], [9,6][9, 6]: 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 ≥1\ge 1); 5 and 9 start piles; 2 goes on the 4 (the leftmost top ≥2\ge 2); 6 goes on the 9. Four non-increasing piles, matching an LIS such as 1,4,5,61, 4, 5, 6, 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 O(nlog⁡n)O(n \log n); negating the values turns every statement into its decreasing mirror image.

The Erdős–Szekeres theorem

DerivationProof by pigeonhole
  1. at ⟼ (it, dt)a_t \ \longmapsto\ (i_t,\ d_t)

    Label each element ata_t with the pair (it,dt)(i_t, d_t): the lengths of a longest increasing and a longest decreasing subsequence ending at ata_t. These are the entries of the two DP tables, one per direction.

  2. u<t ⟹ (iu, du)≠(it, dt)u < t \ \Longrightarrow\ (i_u,\ d_u) \ne (i_t,\ d_t)

    The labels are distinct. For u<tu < t: if au<ata_u < a_t, every increasing subsequence ending at aua_u extends by ata_t, so it>iui_t > i_u; otherwise au>ata_u > a_t, since the values are distinct, and dt>dud_t > d_u by the same argument.

  3. (r−1)(s−1) elements with LIS=r−1 and LDS=s−1(r-1)(s-1) \text{ elements with } \mathrm{LIS} = r - 1 \text{ and } \mathrm{LDS} = s - 1

    If every it≤r−1i_t \le r - 1 and every dt≤s−1d_t \le s - 1, only (r−1)(s−1)(r-1)(s-1) labels exist, fewer than the elements: impossible, by the pigeonhole principle. Tightness: write r−1r - 1 blocks of s−1s - 1 values, each block decreasing and every block above the previous one, such as 3,2,1,6,5,4,9,8,73, 2, 1, 6, 5, 4, 9, 8, 7. 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 n≤LIS⋅LDSn \le \mathrm{LIS} \cdot \mathrm{LDS}, and in particular max⁡(LIS,LDS)≥⌈n⌉\max(\mathrm{LIS}, \mathrm{LDS}) \ge \lceil \sqrt n \rceil.

Predict before you look

What is the smallest nn such that every sequence of nn distinct numbers has a monotone (increasing or decreasing) subsequence of length 5?

Show the answer

17

With r=s=5r = s = 5 the theorem needs more than (5−1)(5−1)=16(5-1)(5-1) = 16 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 E[Ln]/n\mathbb E[L_n]/\sqrt n converges to a constant, and Logan and Shepp and, independently, Vershik and Kerov (both 1977) showed that the constant is 2:

E[Ln]=2n (1+o(1)),Ln−2nn1/6 → d  F2\mathbb{E}[L_n] = 2\sqrt n\,\big(1 + o(1)\big), \qquad \frac{L_n - 2\sqrt n}{n^{1/6}} \ \xrightarrow{\ d\ }\ F_2
The second statement is the Baik–Deift–Johansson theorem (1999): the fluctuations have order n1/6n^{1/6} and follow the Tracy–Widom distribution F2F_2, the law of the largest eigenvalue of a large random Hermitian matrix (the Gaussian unitary ensemble).

The mean of F2F_2 is about −1.77-1.77, so E[Ln]≈2n−1.77 n1/6\mathbb E[L_n] \approx 2\sqrt n - 1.77\, n^{1/6}. A simulation agrees: 200 random permutations of 10410^4 elements had a mean LIS of about 192, against the prediction 200−8.2≈191.8200 - 8.2 \approx 191.8.

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: O(nlog⁡n)O(n \log n) time. bisect_left gives strict increase, bisect_right non-decreasing.
  • Predecessor indices, recorded when an element lands at position kk (pointing at the element in Tk−1T_{k-1}), 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 (r−1)(s−1)(r-1)(s-1) distinct numbers force an increasing subsequence of length rr or a decreasing one of length ss, by pigeonhole on the two DP tables. A random permutation has an LIS of about 2n2\sqrt n with Tracy–Widom fluctuations of order n1/6n^{1/6}, and Θ(nlog⁡n)\Theta(n \log n) 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.

Question 1

The tails are [2,5,9][2, 5, 9] and the next element is 5. What happens in the strict and in the non-decreasing version?

  1. Strict: 5 replaces the 9; non-decreasing: 5 is appended
  2. Strict: nothing changes (5 replaces the equal tail 5); non-decreasing: 5 replaces the 9, giving [2,5,5][2, 5, 5]
  3. Both append 5, giving [2,5,9,5][2, 5, 9, 5]
  4. 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 [2,5,5][2, 5, 5]

bisect_left finds index 1, the first tail ≥5\ge 5: 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 >5> 5: with repeats allowed, 2,5,52, 5, 5 has length 3 and a smaller tail than 9.

Question 2

What is the fewest non-increasing subsequences into which a sequence can be partitioned?

  1. The length of a longest non-increasing subsequence
  2. The length of a longest strictly increasing subsequence
  3. The number of distinct values
  4. 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).

Question 3

Every permutation of 1,2,…,1011, 2, \dots, 101 is guaranteed to contain a monotone subsequence of length at least…

  1. 10
  2. 11
  3. 51
  4. 7, about log⁡2101\log_2 101
Show the answer

B. 11

101>10⋅10101 > 10 \cdot 10, so with r=s=11r = s = 11 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.

Question 4

About how long is a longest increasing subsequence of a uniformly random permutation of 10610^6 numbers?

  1. About 20
  2. About 2,000
  3. About 20,000
  4. About 500,000
Show the answer

B. About 2,000

E[Ln]≈2n−1.77 n1/6=2000−17.7≈1982\mathbb E[L_n] \approx 2\sqrt n - 1.77\,n^{1/6} = 2000 - 17.7 \approx 1982, with fluctuations of order n1/6=10n^{1/6} = 10. The growth is like n\sqrt n: not logarithmic, and far from a constant fraction of nn.

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.