The longest increasing subsequence (LIS) problem asks for the longest set of elements, taken in their original order but not necessarily adjacent, whose values strictly increase. It has a textbook O(n²) DP that teaches the "best answer ending at i" state, and a beautiful O(n log n) algorithm, patience sorting, that combines a greedy invariant with Binary Search. Many problems (nesting envelopes, chains of pairs, mountain arrays) are LIS in disguise.
Think of it like
Patience, the card game
Deal cards one at a time. Each card goes on the leftmost pile whose top card is at least as high as it; if there is no such pile, start a new pile on the right. When the deck runs out, the number of piles equals the length of the longest increasing subsequence of the deal. The O(n log n) algorithm is exactly this game, played with binary search to find the right pile.
The problem
Given nums = [10, 9, 2, 5, 3, 7, 101, 18], the LIS has length 4: for example [2, 3, 7, 101], [2, 5, 7, 101] or [2, 3, 7, 18]. Subsequences keep the original order but may skip elements. Brute force checks all 2ⁿ subsequences; we can do far better.
- Strictly increasing
- Each element is greater than the previous one (
a < b). The default meaning of LIS. - Non-decreasing
- Equal neighbors are allowed (
a ≤ b). A one-character change in the binary search handles it. - Subsequence vs subarray
- A subarray is contiguous. The longest increasing subarray is a simple O(n) scan; the subsequence version needs DP.
The O(n²) DP: best subsequence ending at i
The natural first attempt, "dp[i] = LIS of the prefix nums[0..i]", does not lead to a recurrence: to extend a subsequence with nums[i] you need to know its last value, and the prefix answer forgets it. The fix is to anchor the end.
- 1
State
L[i]= the length of the longest increasing subsequence that ends exactly at index i (so its last value isnums[i]). - 2
Last decision
Which element comes just before
nums[i]? Any earlierjwithnums[j] < nums[i]; extend the best one. If none exists,nums[i]starts a new subsequence. - 3
Base case
Every element alone is a subsequence of length 1, so
L[i]starts at 1. - 4
Order and answer
Increasing
i. The answer ismax(L[i])over alli, notL[n-1], because the LIS can end anywhere.
| i | nums[i] | L[i] | prev[i] | best subsequence ending here |
|---|---|---|---|---|
| 0 | 10 | 1 | - | 10 |
| 1 | 9 | 1 | - | 9 |
| 2 | 2 | 1 | - | 2 |
| 3 | 5 | 2 | 2 | 2, 5 |
| 4 | 3 | 2 | 2 | 2, 3 |
| 5 | 7 | 3 | 3 | 2, 5, 7 |
| 6 | 101 | 4 | 5 | 2, 5, 7, 101 |
| 7 | 18 | 4 | 5 | 2, 5, 7, 18 |
Reconstruction. Store prev[i], the index j that produced L[i]. Find the index with the largest L, follow prev pointers back to -1, and reverse. Use the visualization above to watch both the L values and the predecessor links form.
O(n log n): patience sorting with a tails array
The faster algorithm keeps, for every possible length, the smallest tail value of any increasing subsequence of that length found so far. A smaller tail is always at least as useful as a larger one, because it can be extended by more future elements.
- 1
Find the slot
For each
x, binary search for the first indexkwithtails[k] ≥ x(lower bound). - 2
Extend
If no such index exists,
xis larger than every tail: append it. The LIS just got one longer. - 3
Improve
Otherwise set
tails[k] = x. We found a length-(k+1) subsequence with a smaller ending, which keeps more options open. - 4
Answer
After all elements, the LIS length is
len(tails).
| x | lower bound k | action | tails afterward |
|---|---|---|---|
| 10 | 0 (empty) | append | [10] |
| 9 | 0 | replace 10 | [9] |
| 2 | 0 | replace 9 | [2] |
| 5 | 1 (end) | append | [2, 5] |
| 3 | 1 | replace 5 | [2, 3] |
| 7 | 2 (end) | append | [2, 3, 7] |
| 101 | 3 (end) | append | [2, 3, 7, 101] |
| 18 | 3 | replace 101 | [2, 3, 7, 18] |
Why it works
- tails stays strictly increasing. If
tails[k] ≥ tails[k+1], then the length-(k+2) subsequence ending attails[k+1]contains a length-(k+1) prefix ending at a value smaller thantails[k+1] ≤ tails[k], contradicting the minimality oftails[k]. - Replacing is safe. Overwriting
tails[k]with a smallerxnever removes a length we have achieved; it only lowers the bar for extending that length later. - Appending is exact. We append only when
xbeats every tail, meaningxextends the longest subsequence found so far. - The binary search finds the right pile. This is the patience game: piles correspond to positions in
tails, and the top card of pile k istails[k].
Reconstructing the sequence in O(n log n)
Store indices instead of values: tailIdx[k] is the index of the element currently ending the best length-(k+1) subsequence. When element i lands in slot k, its parent is whatever ends slot k-1 at that moment: parent[i] = tailIdx[k-1]. At the end, start from tailIdx[last] and follow parents.
| i | nums[i] | slot k | parent[i] | tailIdx afterward |
|---|---|---|---|---|
| 0 | 10 | 0 | -1 | [0] |
| 1 | 9 | 0 | -1 | [1] |
| 2 | 2 | 0 | -1 | [2] |
| 3 | 5 | 1 | 2 | [2, 3] |
| 4 | 3 | 1 | 2 | [2, 4] |
| 5 | 7 | 2 | 4 | [2, 4, 5] |
| 6 | 101 | 3 | 5 | [2, 4, 5, 6] |
| 7 | 18 | 3 | 5 | [2, 4, 5, 7] |
Notice the two algorithms returned different (equally long) answers: the O(n²) version found [2, 5, 7, 101] and the patience version [2, 3, 7, 18]. When a problem asks for "any" LIS, both are correct; if it requires a specific one (say lexicographically smallest), you must adapt the tie-breaking.
Variants
Non-decreasing subsequences
To allow equal elements, search for the first tail strictly greater than x (upper bound, bisect_right) instead of the first tail ≥ x. For [2, 2, 2] the strict LIS is 1 and the non-decreasing one is 3. In the O(n²) DP, change nums[j] < nums[i] to ≤.
Number of longest increasing subsequences
Track two arrays: len[i] (as before) and cnt[i], the number of LIS of length len[i] ending at i. When a predecessor j gives a longer length, copy its count; when it ties, add its count.
def find_number_of_lis(nums: list[int]) -> int:
n = len(nums)
length = [1] * n # LIS length ending at i
count = [1] * n # how many LIS of that length end at i
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if length[j] + 1 > length[i]:
length[i], count[i] = length[j] + 1, count[j]
elif length[j] + 1 == length[i]:
count[i] += count[j]
best = max(length, default=0)
return sum(c for l, c in zip(length, count) if l == best)
print(find_number_of_lis([1, 3, 5, 4, 7])) # 2: [1,3,5,7] and [1,3,4,7]| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| nums[i] | 1 | 3 | 5 | 4 | 7 |
| length[i] | 1 | 2 | 3 | 3 | 4 |
| count[i] | 1 | 1 | 1 | 1 | 2 |
Russian doll envelopes
Envelope (w, h) fits inside another only if both dimensions are strictly smaller. How many can be nested? Sort by width ascending, and for equal widths sort by height descending; then the answer is the strict LIS of the heights.
- Sorting by width turns a 2D condition into a 1D one: later envelopes are never narrower.
- Descending heights within a width group make it impossible to pick two envelopes of the same width (their heights decrease, so a strictly increasing sequence takes at most one).
- Example
[[5,4], [6,4], [6,7], [2,3]]sorts to[2,3], [5,4], [6,7], [6,4]; heights[3, 4, 7, 4]have LIS 3:[2,3] → [5,4] → [6,7].
Longest bitonic subsequence
A bitonic sequence increases and then decreases. Compute inc[i] (LIS ending at i, scanning left to right) and dec[i] (longest decreasing subsequence starting at i, which is an LIS scanning right to left). The answer is max(inc[i] + dec[i] − 1), subtracting 1 because the peak is counted twice.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| nums[i] | 1 | 11 | 2 | 10 | 4 | 5 | 2 | 1 |
| inc[i] | 1 | 2 | 2 | 3 | 3 | 4 | 2 | 1 |
| dec[i] | 1 | 5 | 2 | 4 | 3 | 3 | 2 | 1 |
| inc + dec − 1 | 1 | 6 | 3 | 6 | 5 | 6 | 3 | 1 |
More problems that reduce to LIS
- Maximum length of pair chain / box stacking: sort by one key, then LIS (or greedy) on the other.
- Largest divisible subset: sort, then the O(n²) DP with
nums[i] % nums[j] == 0replacing<. - Increasing triplet subsequence: the patience algorithm with only two tails, O(1) space.
- LCS of two permutations: relabel by positions and run LIS, O(n log n); see LCS & Edit Distance.
- Minimum number of increasing subsequences covering the array equals the length of the longest non-increasing subsequence (a consequence of Dilworth's theorem).
Choosing an approach
O(n²) DP
- Simple, easy to modify for custom compatibility rules (divisibility, chains)
- Natural for counting (number of LIS) and weighted versions (maximum-sum increasing subsequence)
- Fine for n up to a few thousand
O(n log n) patience sorting
- Required when n reaches 10⁵ or more
- Needs a total order and a binary-searchable condition
- Reconstruction requires index tracking and parent pointers
- Counting or weighting needs a Fenwick Trees (BIT) or Segment Trees over values instead
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Brute force | O(2ⁿ·n) | O(n) | Check every subsequence |
| DP ending at i | O(n²) | O(n) | Easy to adapt; prev pointers reconstruct |
| Patience sorting | O(n log n) | O(n) | Binary search on tails |
| Patience + reconstruction | O(n log n) | O(n) | tailIdx and parent arrays |
| Number of LIS | O(n²) | O(n) | O(n log n) with a Fenwick or segment tree |
| Russian doll envelopes | O(n log n) | O(n) | Sort, then LIS on heights |
The O(n log n) bound is optimal for comparison-based algorithms.
Implementation
L[i] is the longest increasing subsequence ending at i; prev[i] remembers the predecessor so the sequence can be rebuilt.
def lis_quadratic(nums: list[int]) -> list[int]:
n = len(nums)
if n == 0:
return []
L = [1] * n # L[i] = LIS length ending exactly at i
prev = [-1] * n # predecessor index in that subsequence
for i in range(n):
for j in range(i):
if nums[j] < nums[i] and L[j] + 1 > L[i]:
L[i] = L[j] + 1
prev[i] = j
end = max(range(n), key=lambda i: L[i]) # the LIS can end anywhere
seq = []
while end != -1:
seq.append(nums[end])
end = prev[end]
return seq[::-1]
print(lis_quadratic([10, 9, 2, 5, 3, 7, 101, 18])) # [2, 5, 7, 101]Key takeaways
- Define
L[i]as the LIS ending at i; the answer is the max over all i. That gives an O(n²) DP. - Patience sorting keeps
tails[k], the smallest tail of any increasing subsequence of length k + 1, and binary searches it for O(n log n). tailshas the right length but is generally not a valid subsequence; reconstruct with tail indices and parent pointers.- Lower bound gives strictly increasing; upper bound gives non-decreasing.
- 2D nesting problems become LIS after sorting by one dimension (descending on ties) and running LIS on the other.
Common pitfalls
- Returning
L[n-1]instead ofmax(L). - Printing
tailsas if it were the LIS. - Using
bisect_right/upper_boundwhen the problem requires a strictly increasing sequence (or the reverse). - Sorting Russian doll envelopes with heights ascending for equal widths, which lets two same-width envelopes nest.
- In bitonic problems, forgetting to subtract 1 for the peak counted in both directions.
Interview tips
- Start with the O(n²) DP and its state sentence; then offer the O(n log n) improvement before being asked.
- Explain the tails invariant and why it stays sorted; that is what makes binary search legal.
- Have the
[3, 4, 5, 1]counterexample ready for "is tails the actual subsequence?" - For 2D variants, justify the tie-breaking sort order explicitly; it is the whole trick.
Real-world applications
- Patience diff, used by some version control tools, anchors on unique matching lines found via LIS.
- Scheduling and stacking problems (boxes, envelopes, nested intervals) reduced to chains in a partial order.
- Computing the minimum number of operations to make an array sorted (n minus the longest sorted subsequence that can stay).
- Analyzing trends in time series: the longest run of record highs, ignoring dips.
Practice problems
Test yourself
After running patience sorting on [3, 4, 5, 1], tails is [1, 4, 5]. What does this tell you?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.