Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithm · Dynamic Programming

The Longest Climb.

Watch the explainer

Don't memorize the longest increasing subsequence — watch it build. Pick elements left to right, keeping their order but skipping freely, to form the longest strictly rising run. The trick: the best run ending at an element is just one plus the best run ending on any earlier, smaller element. Fill that in for every position and the answer emerges — then trace the chain back.

subsequence · dp[i] = 1 + max(dp[j]) · O(n²)
SUBSEQUENCE

Keep order, skip freely — elements need not be adjacent.

dp[i]

Length of the longest increasing run that ends at index i.

EXTEND

dp[i] = 1 + the best dp[j] among earlier, smaller values.

ANSWER

The maximum over all dp[i]; trace back to rebuild the run.

lis.sim — array [3,1,4,1,5,9,2,6]
Ready

Top row is the array; bottom row is dp — the longest increasing run ending at each position. Press Step to fill dp left to right; each element extends the best earlier smaller one.

—
dp[i]
1
LIS length

Every ending, its longest run

Trying every subsequence is exponential. The DP insight is to anchor on where a subsequence ends: if you know, for every earlier position, the longest increasing run ending there, then the longest run ending at the current element is one more than the best of those earlier runs whose value is smaller. Compute that left to right and each element only looks back at the ones before it.

01

Start everyone at 1

Every element is an increasing run of length 1 on its own.

02

Look back for smaller

For element i, scan earlier elements j; if A[j] < A[i], you can extend that run.

03

Take the best

dp[i] = 1 + max(dp[j]) over those valid j — the longest run you can extend, plus this element.

04

Read and reconstruct

The largest dp value is the LIS length; follow the recorded predecessors back to list the subsequence.

Time (DP)
O(n²)
Faster
O(n log n)
Space
O(n)
Type
DP

The quadratic DP is the clearest way to see it, but LIS also has a slick O(n log n) solution called patience sorting: keep the smallest possible tail for a run of each length, and binary-search where each new element belongs. The length of that tails array is the LIS length. LIS underlies diff tools, longest-chain scheduling, and the box-stacking and Russian-doll problems.

The picture: dp[i] counts the best run ending at i

Adp 0101191221352432573610147184 one longest chain: 2 → 5 → 7 → 101 (length 4)
The page’s array [10, 9, 2, 5, 3, 7, 101, 18] with dp[i] underneath. The 10 and 9 can only stand alone, so their dp is 1. The 7 at index 5 can extend 5 (dp = 2) to reach 3. The arcs follow the chain of predecessors that the DP recorded for the first index holding the maximum.

Worked example, step by step

Run the O(n log n) patience-sorting method on A = [10, 9, 2, 5, 3, 7, 101, 18]. Keep tails, where tails[k] is the smallest value that can end an increasing subsequence of length k+1. For each element, binary-search the first tail that is ≥ x: replace it, or append if none exists. The last column shows the quadratic DP's dp[i] for comparison.

ixPosition foundActiontails afterLengthdp[i]
0100append[10]11
190replace tails[0] (was 10)[9]11
220replace tails[0] (was 9)[2]11
351append[2, 5]22
431replace tails[1] (was 5)[2, 3]22
572append[2, 3, 7]33
61013append[2, 3, 7, 101]44
7183replace tails[3] (was 101)[2, 3, 7, 18]44

Two things stand out. First, the final length of tails is 4, equal to max(dp): the two methods answer the same question. Second, tails is a set of best end values, not the subsequence itself. Here it finishes as [2, 3, 7, 18], which happens to be a valid chain (indices 2, 4, 5, 7), but it is a different chain from the DP's 2, 5, 7, 101, and in general it need not be one at all (see the mistakes below). Each replacement keeps a tail smaller, which can only make future extensions easier, so overwriting never loses the answer. When 101 arrives it extends the longest run (append); 18 then replaces it with a smaller tail for the same length.

Getting the subsequence back. Keep two extra arrays: the input index sitting at each tail, and a prev link for every element, pointing at the index in the slot to its left when it arrived. On this input prev ends as [−1, −1, −1, 2, 2, 4, 5, 5]. Start from the index at the last tail, 7 (the 18), and follow the links: 7 → 5 → 4 → 2 → stop. Reversed, that is indices 2, 4, 5, 7, the values 2, 3, 7, 18. Every link is fixed when its element arrives, so later replacements in tails cannot corrupt it. That is why this is safe where reading tails is not. It costs O(n) extra space and no extra time.

Complexity and trade-offs

CaseTimeSpaceWhy
Brute force over subsetsO(2ⁿ · n)O(n)Try every subsequence and test it. Unusable beyond about 25 elements.
DP, look back at every jO(n²)O(n)The clearest version. Easy to extend with weights or to rebuild the sequence from predecessors.
Patience sorting + binary searchO(n log n)O(n)One pass; each element does one binary search over tails. Rebuilding the sequence needs extra bookkeeping.
Fenwick or segment tree on valuesO(n log n)O(n)Query the best dp among smaller values. Needed when each element carries a weight, as in maximum-sum increasing subsequence.
LCS with the sorted arrayO(n²)O(n)Valid only for distinct values: LIS(A) = LCS(A, sorted(A)). A neat equivalence, but slower than patience sorting.

In the comparison model O(n log n) is also the lower bound (Fredman, 1975), so patience sorting is optimal for length. Pick the quadratic DP when the input is small, when you need the weighted variant without a tree, or when readability matters more than speed.

Common mistakes

  • Using the wrong binary search for strictness

    For a strictly increasing subsequence, replace the first tail ≥ x (bisect_left). With bisect_right equal values extend the run: on [2, 2, 2] it returns 3 instead of 1. It is the right choice only if you want a non-decreasing subsequence.

  • Reading tails as the answer

    tails holds the best end values, not a real subsequence. On [1, 3, 5, 2] it finishes as [1, 2, 5], yet 2 comes after 5, so 1, 2, 5 is not an increasing subsequence of the input. The length is right; the contents are not. Store a predecessor index per element if you need the sequence.

  • Returning dp[n−1] instead of max(dp)

    dp[i] is the best run ending at i. On [1, 2, 3, 0] the table is [1, 2, 3, 1]; the last entry is 1 but the answer is 3.

  • Starting dp at 0

    Every element is a run of length 1 by itself. Initialising dp with zeros makes the page’s array answer 3 instead of 4, so the result is always one short.

  • Confusing subsequence with subarray

    A subsequence may skip elements. On [1, 3, 2, 4] the longest increasing subarray has length 2, but the longest increasing subsequence is 3 (1, 3, 4 or 1, 2, 4).

Where this shows up

  • Nested-envelope and stacking problems

    “Russian doll envelopes” sorts by width ascending and, for ties, height descending, then takes the LIS of the heights. Box stacking and “longest chain of pairs” reduce to the same kernel.

  • Patience sorting and card games

    The tails array is the top row of piles in the card game patience: place each card on the leftmost pile whose top is not smaller. The number of piles equals the LIS length.

  • Combinatorics

    The Erdős–Szekeres theorem says any sequence of more than r·s distinct numbers contains an increasing run of length r+1 or a decreasing one of length s+1. Schensted’s algorithm links LIS length to the shape of a Young tableau.

  • Diff and sequence alignment

    The Hunt–Szymanski algorithm for longest common subsequence searches over increasing sequences of match positions, which is why LIS-style binary search appears inside file-comparison tools.

SOLVE IT YOURSELF

Solve it: longest increasing subsequence

This one is yours to write — in Python or TypeScript, running for real in your browser. Edit the stub below, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are below and Reveal solution is one click away.

YOUR TASK

Implement lis_length(nums): return the length of the longest strictly increasing subsequence (keep order, drop elements freely). The classic dynamic program is O(n²): dp[i] = longest increasing run ending at i.

HINTS — 4 IDEAS
  1. Let dp[i] be the length of the longest increasing subsequence that ends at index i. Every element alone is length 1.
  2. For each i, look back at every j < i: if nums[j] < nums[i], you can extend that run — dp[i] = max(dp[i], dp[j] + 1).
  3. The answer is the largest value in dp.
  4. An empty array has length 0. (A faster O(n log n) patience-sorting version exists, but O(n²) is the clean starting point.)
CPython · WebAssembly

Check yourself

1 · What is dp[i] in the LIS dynamic program?

Each dp cell is the best increasing run that finishes exactly at that position.

2 · How is dp[i] computed?

Extend the best earlier run that ends on a smaller value; if none, dp[i] stays 1.

3 · What is the fast LIS complexity, and how?

Maintaining tails of each run length and binary-searching each element gives O(n log n).

Questions

Subsequence vs substring?

A substring is contiguous; a subsequence keeps order but may skip elements. LIS is about subsequences, so 3, 4, 5, 9 counts even though those values are not next to each other in the array.

Strictly vs non-decreasing?

Strictly increasing forbids equal neighbors (use A[j] < A[i]); the longest non-decreasing variant allows equals (A[j] ≤ A[i]). Same algorithm, one comparison changed.

How does patience sorting give the length?

Deal cards into piles where each card goes on the leftmost pile whose top is greater or equal (a binary search); the number of piles equals the LIS length. It is the same idea as the tails array in the O(n log n) method.

Anchor on the ending, extend the best.

Each element adds one to the longest smaller run before it. The max is your longest climb.

▶  Watch it explained

Longest Increasing Subsequence: Why the Tails Array Lies

Finished this one? 0 / 99 Algorithms done
NextThe Typo Fixer: Edit Distance Closest algorithm to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms