Longest Increasing Subsequence
The longest increasing subsequence (LIS) is the longest run of values, in their original order, where each is larger than the one before. A look-back DP finds its length in O(n²); keeping only the smallest possible ending for every length, and placing each new value by binary search, brings it to O(n log n).
What the Problem Asks
Given a sequence, pick some of its values, keeping their order, so that each picked value is larger than the one before. The longest such pick is a longest increasing subsequence. For 5, 2, 8, 6, 3, 6, 9, 7 one answer is 2, 3, 6, 7 (length 4); 2, 3, 6, 9 is another. The length is unique, the subsequence is not.
A subsequence is not a subarray: the values need not be next to each other. 'Increasing' usually means strictly, so equal values cannot both be used. The variant that allows equal values is covered below.
- Input: n numbers in a fixed order
- Output: the length, and often one subsequence of that length
- Brute force tries all 2ⁿ subsets; two better methods follow
The O(n²) DP and Its Limit
Let dp[i] be the length of the longest increasing subsequence that ends exactly at index i. It is 1 plus the best dp[j] over all earlier j with a smaller value, or just 1 if there is none. The answer is the largest dp[i], not the last one. This is the look-back-over-everything pattern from one-dimensional dynamic programming.
It is easy to derive and easy to adapt: counting how many longest subsequences exist, or weighting each value, changes one line. But every i scans every j before it, so n = 100,000 means about five billion comparisons. The faster method changes what is stored.
- dp[i] = 1 + max(dp[j]) over j < i with a[j] < a[i]
- O(n²) time, O(n) space
- Keep parent[i] = the j that won, to print the subsequence later
Keep Only the Smallest Ending
- Start with an empty tails list
- For each value x, binary search for the first position k with tails[k] ≥ x
- If k is past the end, append x: some run just grew one longer
- Otherwise set tails[k] = x: runs of length k + 1 can now end lower
- When the input ends, the length of tails is the answer
Suppose two increasing subsequences have the same length, one ending in 8 and one ending in 3. Any later value that extends the 8-run also extends the 3-run, but not the other way round. So for each length, only the subsequence with the smallest last value is worth remembering.
Write tails[k] for the smallest last value among increasing subsequences of length k + 1 seen so far. These values are strictly increasing along the list: the run of length k + 1 that ends in tails[k] contains a run of length k ending in something smaller, so tails[k − 1] is smaller still. A sorted list is what makes binary search possible.
- Each value costs one binary search: LIS in n log n overall
- The list stays sorted after every step, so the search is always valid
- In Python this is bisect_left; in C++ lower_bound; in Java a short manual search
Terms, operations, and practical uses
Key terms
- SubsequenceValues taken in their original order, possibly with gaps.
- tails[k]Smallest last value of any increasing subsequence of length k + 1 so far.
- PileIn patience sorting, a stack of cards placed in decreasing order.
- Parent linkThe index each value extended, used to print the subsequence.
Related lessons and problems
- One-Dimensional Dynamic ProgrammingThe look-back DP behind the O(n²) method.
- Binary SearchThe lower-bound search used for each value.
- Dynamic ProgrammingStates, recurrences and the general method.
- Longest Increasing Subsequence (problem)LeetCode 300 with tests.
Code in Python, C++ and Java
from bisect import bisect_left, bisect_right
def lis(nums, strict=True):
search = bisect_left if strict else bisect_right
tail_values, tail_index = [], []
parent = [-1] * len(nums)
for i, x in enumerate(nums):
k = search(tail_values, x)
if k > 0:
parent[i] = tail_index[k - 1]
if k == len(tail_values):
tail_values.append(x)
tail_index.append(i)
else:
tail_values[k] = x
tail_index[k] = i
seq, i = [], tail_index[-1] if tail_index else -1
while i != -1:
seq.append(nums[i])
i = parent[i]
return seq[::-1], tail_values
def show(name, nums, strict=True):
seq, tails = lis(nums, strict)
print(f"{name}: length {len(seq)}, sequence {seq}, tails {tails}")
show("cards", [5, 2, 8, 6, 3, 6, 9, 7])
show("cards + 1", [5, 2, 8, 6, 3, 6, 9, 7, 1])
show("equal, strict", [4, 4, 4])
show("equal, non-decreasing", [4, 4, 4], strict=False)
show("decreasing", [9, 7, 4, 1])
show("empty", [])#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void printList(const vector<int>& v) {
cout << "[";
for (size_t i = 0; i < v.size(); i++) cout << (i ? ", " : "") << v[i];
cout << "]";
}
void show(const string& name, const vector<int>& nums, bool strict = true) {
vector<int> tailValues, tailIndex, parent(nums.size(), -1);
for (int i = 0; i < (int)nums.size(); i++) {
int x = nums[i];
auto it = strict ? lower_bound(tailValues.begin(), tailValues.end(), x)
: upper_bound(tailValues.begin(), tailValues.end(), x);
int k = it - tailValues.begin();
if (k > 0) parent[i] = tailIndex[k - 1];
if (k == (int)tailValues.size()) {
tailValues.push_back(x);
tailIndex.push_back(i);
} else {
tailValues[k] = x;
tailIndex[k] = i;
}
}
vector<int> seq;
for (int i = tailIndex.empty() ? -1 : tailIndex.back(); i != -1; i = parent[i]) seq.push_back(nums[i]);
reverse(seq.begin(), seq.end());
cout << name << ": length " << seq.size() << ", sequence ";
printList(seq);
cout << ", tails ";
printList(tailValues);
cout << "\n";
}
int main() {
show("cards", {5, 2, 8, 6, 3, 6, 9, 7});
show("cards + 1", {5, 2, 8, 6, 3, 6, 9, 7, 1});
show("equal, strict", {4, 4, 4});
show("equal, non-decreasing", {4, 4, 4}, false);
show("decreasing", {9, 7, 4, 1});
show("empty", {});
}import java.util.*;
public class Main {
static void show(String name, int[] nums, boolean strict) {
int n = nums.length, size = 0;
int[] tailValues = new int[n], tailIndex = new int[n], parent = new int[n];
for (int i = 0; i < n; i++) {
int x = nums[i], lo = 0, hi = size;
while (lo < hi) {
int mid = (lo + hi) / 2;
boolean goRight = strict ? tailValues[mid] < x : tailValues[mid] <= x;
if (goRight) lo = mid + 1;
else hi = mid;
}
parent[i] = lo > 0 ? tailIndex[lo - 1] : -1;
tailValues[lo] = x;
tailIndex[lo] = i;
if (lo == size) size++;
}
List<Integer> seq = new ArrayList<>();
for (int i = size == 0 ? -1 : tailIndex[size - 1]; i != -1; i = parent[i]) seq.add(nums[i]);
Collections.reverse(seq);
List<Integer> tails = new ArrayList<>();
for (int k = 0; k < size; k++) tails.add(tailValues[k]);
System.out.println(name + ": length " + seq.size() + ", sequence " + seq + ", tails " + tails);
}
public static void main(String[] args) {
show("cards", new int[]{5, 2, 8, 6, 3, 6, 9, 7}, true);
show("cards + 1", new int[]{5, 2, 8, 6, 3, 6, 9, 7, 1}, true);
show("equal, strict", new int[]{4, 4, 4}, true);
show("equal, non-decreasing", new int[]{4, 4, 4}, false);
show("decreasing", new int[]{9, 7, 4, 1}, true);
show("empty", new int[]{}, true);
}
}Step through it
Running on values 5, 2, 8, 6, 3, 6, 9, 7
The Card Game Behind It
The same procedure is called patience sorting, after a solitaire game. Deal the values one at a time as cards. Each card goes on the leftmost pile whose top card is not smaller than it; if no pile qualifies, it starts a new pile on the right. The tops of the piles, read left to right, are exactly the tails list, and the number of piles is the length of the longest increasing subsequence.
The piles also explain why the answer cannot be longer. Each card went on a top at least as big as itself, so values never increase from the bottom of a pile to its top, and an increasing subsequence can use at most one card from each pile. Four piles, at most four cards. The diagram above shows the piles for 5, 2, 8, 6, 3, 6, 9, 7.
- Number of piles = LIS length
- Each pile never increases, so the piles also split the input into the fewest such non-increasing runs
- Collecting the piles and merging them sorts the cards, which is where the name comes from
How to Print the Longest Increasing Subsequence
The tails list is not an answer you can print. Add 1 to the end of the example and tails becomes 1, 3, 6, 7: right length, but 1 comes after 7 in the input. Only the length is guaranteed.
To print the longest increasing subsequence, store indices instead of values in tails, and when a value is placed at position k, record parent = the index currently at tails[k − 1] (the card on top of the pile to its left). At the end, start from the index at the last position and follow parents back to the start, then reverse.
- Parents always point to an earlier index with a smaller value, so the walk back is a valid subsequence
- Extra cost: one array of n indices
- In the example the walk goes 7 → 6 → 3 → 2, printed as 2, 3, 6, 7
Variants
For the longest non-decreasing subsequence, where equal values may follow each other, search for the first tail strictly greater than x (bisect_right, upper_bound) instead. Using that search by mistake on the strict problem is the most common bug: 4, 4, 4 would give 3 instead of 1.
Other questions reduce to this one. The longest decreasing subsequence is the LIS of the negated values. The fewest deletions to make a sequence sorted is n minus the LIS length. Nesting envelopes (Russian doll) sorts by width ascending and, for equal widths, height descending, then takes the LIS of the heights; the descending tie-break stops two envelopes of the same width from nesting.
- Non-decreasing: upper bound instead of lower bound
- Decreasing: negate the values first
- Two dimensions: sort one, run LIS on the other
- Counting the longest subsequences: use the O(n²) DP with a count per index
Problems to Practise
Start with the plain length, then try variants that change what is extended or added up.
- Longest Increasing Subsequence: length in O(n log n)
- Increasing Triplet Subsequence: the tails list capped at two entries
- Maximum Sum Increasing Subsequence: the O(n²) DP with sums instead of lengths
- Largest Divisible Subset: after sorting, the same DP with 'divides' in place of 'smaller'