V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Longest Increasing Subsequence

One-dimensional DP with predecessor reconstruction

End each subproblem at a specific index

Let dp[i] be the length of the longest strictly increasing subsequence that ends at index i. Every value can stand alone, so all entries start at 1. To solve dp[i], inspect every earlier index j.

Extend only from a smaller value

If a[j] < a[i], an increasing subsequence ending at j can accept a[i]. Update dp[i] with dp[j] + 1 when it is larger, and remember j as the predecessor. The largest DP entry gives the global length.

The two-row matrix shows input values above their DP lengths. Yellow cells identify the value and predecessor under comparison, green marks an improvement, and the final highlighted value path follows predecessors back to one optimal sequence.

012345
Value132435
dp111111

Initialize every dp[i] to 1 because each value forms a length-one subsequence.

1function longestIncreasingSubseq(a: number[]): number[] {
2 const n = a.length;
3 const dp = new Array(n).fill(1); // each element alone has length 1
4 const pred = new Array(n).fill(-1);
5 for (let i = 1; i < n; i++) {
6 for (let j = 0; j < i; j++) {
7 if (a[j] < a[i] && dp[j] + 1 > dp[i]) { // can extend to a longer sequence
8 dp[i] = dp[j] + 1;
9 pred[i] = j;
10 }
11 }
12 }
13 let best = 0;
14 for (let i = 1; i < n; i++) if (dp[i] > dp[best]) best = i; // find the best ending position
15 const lis: number[] = [];
16 for (let k = best; k !== -1; k = pred[k]) lis.unshift(a[k]); // reconstruct through predecessors
17 return lis;
18}
Input1 3 2 4 3 5
dp1 1 1 1 1 1
1 / 18

The transparent quadratic solution

Comparing each pair with j < i takes O(n^2) time and O(n) space. A patience-sorting method with binary search reaches O(n log n), but this DP makes the ending-index state and reconstruction invariant explicit.

Invariant: after index i is processed, dp[i] is optimal among all increasing subsequences whose final value is a[i].

Compare one-sequence predecessor links with the two-string trace in Longest Common Subsequence.