Longest Increasing Subsequence
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The longest increasing subsequence is the longest run of values in a list that keep rising, picked in order with gaps allowed. For each item you look at earlier smaller items and build on the best one. It finds steady growth hidden inside noisy data.
Practical use cases
- Web app: Steady rise in daily temperatures or sales. A weather or sales dashboard has a noisy list of daily readings and wants to show the longest run of days that kept rising, ignoring dips in between. For 365 values, each day checks earlier lower days and adds one to the best. The chart highlights the rising days.
- Web app: Nesting boxes in a shipping calculator. A logistics tool has boxes with sizes and wants to know the longest chain where each box fits inside the next. After sorting by one dimension, the problem becomes a longest increasing run on the other. The warehouse knows how many boxes it can nest.
- System: Patience sorting and version tracking. A card game called patience gives a clever way to find this run quickly. Version tracking and stock trend tools use the same idea to find long upward trends.
The story: The Staircase of Hill Posts
On a hill trail near Mussoorie, Mira noticed milestone posts of different heights: 10, 9, 2, 5, 3, 7, 101, 18. Kabir dared her: "Pick as many posts as you can, walking only forward, so each chosen post is taller than the one before. Skipping posts is allowed. How long can your staircase be?"
Trying every subset was hopeless: eight posts already give 256 subsets. Mira thought small. "For each post, what is the longest staircase that ends exactly here?" The first post alone is a staircase of 1. For any later post, look back at every shorter post: stand on the best of them and step up. So the answer for a post is 1 + the best staircase among shorter posts to its left.
She filled one strip of numbers: 1, 1, 1, 2, 2, 3, 4, 4. The answer was the largest number on the strip: 4 (for example 2, 3, 7, 18). Notice it is not the last cell; the staircase can end anywhere. That is the Longest Increasing Subsequence.
How to spot this problem, and where you need it
You have a list of numbers in time or position order and want the longest group that keeps going up, even when other values interrupt it.
Signs you need it
- The problem says "longest increasing subsequence" or "longest chain" where each item must be larger than the one before.
- Items can be skipped, so a simple scan for consecutive increases does not give the right answer.
- Comparing every pair of items is easy to write but slows down badly with 100,000 items.
Where to use it in a project
- Trend highlighting in analytics, finance and weather dashboards.
- Chaining or nesting items, such as boxes, envelopes or tasks with dependencies.
The solution
Make a list where entry i is the longest rising run that ends at item i. Start every entry at 1. For each item, look at all earlier items that are smaller; take the largest entry among them and add 1. The biggest entry in the list is the answer. For very long lists, a faster version keeps a list of the smallest possible ending value for each run length and uses binary search to update it.
Payoff: Before: checking every subsequence, over a million for 20 days. After: about 200 comparisons, or far fewer with the faster version.
Explain it like I am 8
Every post asks its friends on the left, "who is shorter than me, and how many steps have you got?" It stands on top of the friend with the most steps and adds one. Then you look around for the post with the most steps overall.
How it works, step by step
- Make a strip
dp[i]= longest increasing run that ends exactly at positioni. Everyone starts at 1. - For each position
i, look at every earlierj. - If
a[j] < a[i], you can step up fromj:dp[i] = max(dp[i], dp[j] + 1). - After the double loop, the answer is the maximum of the whole strip.
- A cleverer version keeps a sorted list of "smallest tail per length" and uses binary search to reach O(n log n). The strip version above is simpler and clearer.
The code in four languages
PHP
<?php
// Length of the longest strictly increasing subsequence.
function lis(array $a): int {
$n = count($a);
if ($n === 0) return 0;
$dp = array_fill(0, $n, 1); // every element alone is a staircase of 1
for ($i = 1; $i < $n; $i++) {
for ($j = 0; $j < $i; $j++) {
if ($a[$j] < $a[$i]) { // we can step up from j to i
$dp[$i] = max($dp[$i], $dp[$j] + 1);
}
}
}
return max($dp); // the staircase may end anywhere
}
echo lis([10, 9, 2, 5, 3, 7, 101, 18]), "\n"; // 4JavaScript
// Length of the longest strictly increasing subsequence.
function lis(a) {
const n = a.length;
if (n === 0) return 0;
const dp = new Array(n).fill(1); // every element alone is a staircase of 1
for (let i = 1; i < n; i++) {
for (let j = 0; j < i; j++) {
if (a[j] < a[i]) { // we can step up from j to i
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return Math.max(...dp); // the staircase may end anywhere
}
console.log(lis([10, 9, 2, 5, 3, 7, 101, 18])); // 4Java
import java.util.*;
public class Main {
// Length of the longest strictly increasing subsequence.
static int lis(int[] a) {
int n = a.length;
if (n == 0) return 0;
int[] dp = new int[n];
Arrays.fill(dp, 1); // every element alone is a staircase of 1
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[j] < a[i]) { // we can step up from j to i
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
return Arrays.stream(dp).max().getAsInt(); // the staircase may end anywhere
}
public static void main(String[] args) {
System.out.println(lis(new int[]{10, 9, 2, 5, 3, 7, 101, 18})); // 4
}
}Go
package main
import "fmt"
// Length of the longest strictly increasing subsequence.
func lis(a []int) int {
n := len(a)
if n == 0 {
return 0
}
dp := make([]int, n)
for i := range dp {
dp[i] = 1 // every element alone is a staircase of 1
}
best := 1
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
if a[j] < a[i] { // we can step up from j to i
dp[i] = max(dp[i], dp[j]+1)
}
}
best = max(best, dp[i]) // the staircase may end anywhere
}
return best
}
func main() {
fmt.Println(lis([]int{10, 9, 2, 5, 3, 7, 101, 18})) // 4
}Time: O(n²) · Extra space: O(n). Two nested loops here; the binary-search tails method brings the time down to O(n log n).
Watch out for
- Returning dp[n-1] instead of the maximum of the strip.
- Mixing up subsequence and subarray: here elements need not be neighbours.
- Using ≤ when the problem asks for strictly increasing (equal heights are not a step up).
Quick check
- What does dp[i] store?
- The longest staircase that ends exactly at i
- The longest staircase anywhere in the first i posts, starting anywhere
- The height of post i
- Where is the final answer?
- Last cell
- First cell
- The largest value in the strip
- Longest increasing subsequence length for [3, 2, 1]?
- 3
- 1
- 0