Learn the pattern · ~14 min
Longest Increasing Subsequence
also called patience sorting, chain DP
For every possible length, remember only the smallest number a run of that length can end on. Each new number either extends the longest run or lowers one of those endings.
Reach for it when you read
- +"The longest subsequence (keep the order, gaps allowed) where each next element is bigger."
- +Chains: pairs, envelopes, boxes or words where each one must fit after the previous one.
- +Sort first, then a longest chain: a divisible subset, pair chains, envelopes by width then height.
- +"How many longest increasing subsequences?": the same dp with a count beside it.
- +n up to 2 × 10⁵ and "longest increasing": the O(n log n) tails trick, not the n² loop.
Not this one when
- ×The longest increasing subarray (contiguous): one pass, reset the length on every drop.
- ×A common subsequence of two sequences: LCS over prefix pairs.
- ×For each element the next bigger one: a monotonic stack, not a subsequence.
Learn Longest Increasing Subsequence
First, what does "increasing subsequence" mean?
A subsequence keeps some elements of an array in their order, skipping any in between. From [4, 1, 6, 3] you can take [4, 6] or [1, 3], but not [3, 1]: that flips the order.
It's increasing if every element is strictly bigger than the one before: [1, 3] is; [4, 3] and [2, 2] aren't (unless a problem says "non-decreasing").
The LIS is the longest increasing subsequence.
The problem
[4, 1, 6, 3, 5, 2, 7, 4]. How long is the longest increasing subsequence? By hand:
| try | length | how you found it |
|---|---|---|
| 4, 6, 7 | 3 | from the first element, the next bigger one each time |
| 1, 6, 7 | 3 | start lower, but the 6 jumps too high |
| 1, 3, 5, 7 | 4 | start at 1, climb in small steps |
The answer is 4: 1, 3, 5, 7. The second row shows the trap: a big number early blocks later ones. 8 numbers already have 35 increasing subsequences.
One choice per element
Ask every element one question: what's the longest increasing run that ends right here?
A run ending at
a[i]is eithera[i]alone, ora[i]put after a run ending at some earlier, smallera[j].
Write L(i) for that length. Then L(i) = 1 + max L(j) over j < i with a[j] < a[i] (or 1 if there's no such j). The run must end somewhere, so the answer is the biggest L(i) of all.
For example, the 5 at index 4 can follow 4, 1 or 3. The run ending at 3 is the longest (1, 3), so L(4) = 3.
The brute force: the plain recursion
// L(i) = length of the longest increasing run that ends at a[i]
int L(int i, const vector<int>& a) {
int best = 1; // a[i] alone
for (int j = 0; j < i; j++)
if (a[j] < a[i])
best = max(best, 1 + L(j, a)); // put a[i] after a run ending at a[j]
return best;
}
// answer = max of L(i) over every iIt returns 4. The calls for L(4), the 5:
- L(4) ends at 5: smaller ones before it are 4, 1, 3
- L(0) ends at 4: nothing smaller before it → 1
- L(1) ends at 1: nothing smaller before it → 1← here
- L(3) ends at 3: only 1 is smaller
- L(1) ends at 1 → 1← and here
On a sorted array every call calls all the ones before it: 30 sorted numbers make 2³⁰ − 1, about 10⁹ calls (1.7 seconds), and the problem allows 2500. Time limit exceeded.
The one thought: the same question comes back
L(1) is asked twice inside L(4) alone, and 15 times on the whole array, always giving 1.
L(i) depends only on i: just n different questions, each needing only answers to its left. Fill them left to right:
int lisSlow(const vector<int>& a) {
int n = a.size(), best = 0;
vector<int> dp(n, 1); // dp[i] = L(i), filled left to right
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++)
if (a[j] < a[i]) dp[i] = max(dp[i], dp[j] + 1);
best = max(best, dp[i]);
}
return best;
}| i | a[i] | what happens | dp[i] |
|---|---|---|---|
| 0 | 4 | nothing before it | 1 |
| 1 | 1 | nothing smaller before it | 1 |
| 2 | 6 | after 4 (1) or 1 (1): 1 + 1 | 2 |
| 3 | 3 | after 1 (1) | 2 |
| 4 | 5 | after 4 (1), 1 (1) or 3 (2): best is 3 | 3 |
| 5 | 2 | after 1 (1) | 2 |
| 6 | 7 | after 4, 1, 6, 3, 5, 2; best is 5 (3) | 4 |
| 7 | 4 | after 1 (1), 3 (2) or 2 (2) | 3 |
The biggest cell is 4, the same answer as the brute force. Each element looks at all the ones before it: about n²/2 steps. That's 3 × 10⁶ for n = 2500, but 2 × 10¹⁰ for n = 2 × 10⁵ (10⁵ already takes 7 seconds): too slow.
The second thought: keep only the smallest ends
Stop after 4, 1, 6, 3. The runs of length 2 so far are 4, 6, 1, 6 and 1, 3: two end at 6, one at 3.
Now take any later number x:
- If x can extend a run ending at 6, then x > 6, so x > 3 too: it can extend
1, 3just as well. - If x is 4, 5 or 6, it can extend
1, 3but not the runs ending at 6.
So for length 2, the run ending at 3 is never worse: throw the others away. For each length keep one number, the smallest end of any run that long: tails[k] for length k + 1.
tails is always increasing (drop the last element of a run and you get a shorter run with a smaller end), so binary search finds where x goes. If x is bigger than every tail, it makes a longer run: append. Otherwise it replaces the first tail ≥ x: it extends the run just shorter than that, giving the same length with a smaller end.
int lis(const vector<int>& a) {
vector<int> tails; // tails[k] = smallest end of a run of length k + 1
for (int x : a) {
auto it = lower_bound(tails.begin(), tails.end(), x); // first tail >= x
if (it == tails.end()) tails.push_back(x); // x beats every tail: a longer run
else *it = x; // same length, smaller end
}
return tails.size();
}| x | what happens | tails |
|---|---|---|
| 4 | empty: append | 4 |
| 1 | first tail ≥ 1 is 4: replace it | 1 |
| 6 | bigger than all: append | 1, 6 |
| 3 | first tail ≥ 3 is 6: replace it | 1, 3 |
| 5 | bigger than all: append | 1, 3, 5 |
| 2 | first tail ≥ 2 is 3: replace it | 1, 2, 5 |
| 7 | bigger than all: append | 1, 2, 5, 7 |
| 4 | first tail ≥ 4 is 5: replace it | 1, 2, 4, 7 |
Length 4, the same answer. Careful: 1, 2, 4, 7 is not a real subsequence (the 4 comes after the 7 in the array). tails gives the right length, not the run itself.
Why it's O(n log n)
Count per element: one binary search over tails (at most n long) and one write. O(n log n) time, about 3.5 × 10⁶ steps for n = 2 × 10⁵, and O(n) space.
From 2ⁿ calls to n² cells with the repeated question, then to n log n by keeping only the smallest end per length.
Equal values allowed? Use upper_bound
For the longest non-decreasing subsequence, an equal value may follow: replace the first tail > x instead:
auto it = upper_bound(tails.begin(), tails.end(), x); // first tail > x: equal values may followOn [2, 2, 2], lower_bound gives 1 (strict) and upper_bound gives 3. Picking the wrong one is the most common LIS bug.
Need the run itself? Store parents
The O(n²) table can remember who each element followed, then walk back from the best cell:
vector<int> dp(n, 1), parent(n, -1);
for (int i = 0; i < n; i++)
for (int j = 0; j < i; j++)
if (a[j] < a[i] && dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
parent[i] = j; // a[i] came after a[j]
}
int end = max_element(dp.begin(), dp.end()) - dp.begin();
vector<int> run;
for (int i = end; i != -1; i = parent[i]) run.push_back(a[i]);
reverse(run.begin(), run.end());On our array it rebuilds 1, 3, 5, 7.
Two dimensions? Sort, then LIS
Russian Doll Envelopes: an envelope fits in another if both width and height are strictly smaller. Sort by width, then run LIS on the heights. The trick is equal widths: sort their heights down, so their heights never rise and a strict run takes at most one of them.
sort(env.begin(), env.end(), [](auto& p, auto& q) {
return p[0] != q[0] ? p[0] < q[0] : p[1] > q[1]; // width up; equal width: height down
});
vector<int> h;
for (auto& e : env) h.push_back(e[1]);
return lis(h); // strict LIS on the heightsOn [3,2], [4,5], [4,6], [6,7] this gives 3. Sort equal widths up instead and the heights read 2, 5, 6, 7: LIS 4, nesting [4,5] inside [4,6], which isn't allowed.
Remember this
- "Longest chain where each next one is bigger, fits, or may follow":
dp[i]= the best run ending at i, and the answer is the max over all i, notdp[n − 1]. - Strict increase:
lower_bound. Non-decreasing:upper_bound. tailsgives only the length; store parents in the O(n²) version to print the run.- n up to a few thousand: the O(n²) table is fine. n around 10⁵: tails and binary search.
Practise it on Longest Increasing Subsequence, then Maximum Length of Pair Chain (a different "may follow" rule), Largest Divisible Subset (rebuild the run), Number of Longest Increasing Subsequence (count beside the length) and Russian Doll Envelopes (two dimensions).
Below, watch Longest Increasing Subsequence run line by line.
Watch it work, line by line
Longest Increasing Subsequence ↗, nums = [10, 9, 2, 5, 3, 7, 101, 18] → 4 (2, 3, 7, 18). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Am I choosing the longest chain from one sequence, keeping the original order, where each item must beat the previous one by some rule?
Reach for it when
- +longest chain under a partial order (increasing, divisible, nested envelopes)
- +minimum deletions to make sorted
- +n up to 2e5 needs O(n log n)
It fails when
- ×You're comparing two sequencesuse LCS-family 2-D DP
- ×You need a contiguous increasing run (subarray, not subsequence)use Linear scan
- ×Chaining intervalsuse Greedy by end time, simpler
- ×You need to count LIS in O(n log n)use BIT/segment tree over values
Looks like it, isn't (and the other way round)
- Russian Doll Envelopes looks like Greedy, needs this pattern
Greedy by width fails; sort (w asc, h desc) and run LIS on heights.
- Maximum Length of Pair Chain looks like Longest Increasing Subsequence, needs Interval Scheduling (sort by end)
LIS DP works in O(n2) but sorting by end and greedy is optimal in O(n log n).
- Sequence looks like Longest Increasing Subsequence, needs Slope Trick
Keeping a longest non-decreasing subsequence is wrong (cost is total |change|). Use DP over values, or the slope-trick heap.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What exactly does
tails[k]hold?RevealThe smallest number that ends any increasing run of length k + 1 seen so far.
2lower_bound or upper_bound?Reveal
lower_boundfor strictly increasing runs,upper_boundwhen equal values are allowed.3Is
tailsthe longest increasing subsequence itself?RevealNo. Only its length is guaranteed. Rebuild the run with parent pointers.
4Why does dp[i] mean "longest run ending at a[i]", not "longest run in the first i elements"?Reveal
To extend a run you need its last value. A prefix answer forgets which value it ends on, so it can't be extended; pinning the end keeps it.
Practice ladder
- 1Longest Increasing Subsequencethe hookMedium
- 2Increasing Subsequencebig nMedium
- 3Maximum Length of Pair Chaindifferent ruleMedium
- 4Largest Divisible Subsetrebuild the runMedium
- 5Number of Longest Increasing SubsequencecountMedium
- 6Longest String Chainpredecessors by keyMedium
- 7Russian Doll Envelopestwo dimensionsHard
- 8Increasing Subsequence IIcount, big nHard
Finished Longest Increasing Subsequence? Mark it done and Lessgo moves you to the next step.