Longest Increasing SubsequenceLoading saved progress…

Longest Increasing Subsequence

Given an array of numbers, longestIncreasingSubsequence(nums) returns the length of the longest subsequence whose values strictly increase from left to right. A subsequence keeps the original order but is allowed to skip elements — you can drop any numbers you like, but you cannot reorder the ones you keep. This shows up whenever you care about the longest run of "things only getting bigger" inside a fixed timeline: the longest stretch of months with rising revenue, the deepest chain of versions where each depends on an older one, the longest hand of cards you can play in increasing rank without rearranging the deck.

Signature

// nums: number[] — the input array (may be empty, may contain negatives or duplicates).
// returns: number — the LENGTH of the longest strictly increasing subsequence.
//   Returns the length, NOT the subsequence itself.
function longestIncreasingSubsequence(nums: number[]): number;

Examples

// Classic mixed case. One longest subsequence is [2, 5, 7, 101] (length 4).
// [2, 3, 7, 18] also works — there can be several, but the LENGTH is unique.
longestIncreasingSubsequence([10, 9, 2, 5, 3, 7, 101, 18]); // → 4
// Strictly increasing means equal values DON'T extend the run.
longestIncreasingSubsequence([1, 2, 2, 3]); // → 3   ([1, 2, 3] — only one of the 2s counts)
longestIncreasingSubsequence([7, 7, 7, 7]); // → 1   (a single 7 is the best you can do)
longestIncreasingSubsequence([]);           // → 0

Notes

  • Subsequence, not substring. The chosen elements need not be adjacent in nums. [0, 1, 0, 3, 2, 3] has answer 4 via [0, 1, 2, 3], even though those values are scattered.
  • Strictly increasing. Each kept element must be greater than the one before it. Equal values cannot sit next to each other in the subsequence, so duplicates never lengthen a run.
  • Order is fixed. You may delete elements but never reorder them. Sorting nums first changes the answer — don't.
  • Return the length, not the sequence. Reconstructing one actual subsequence is a fun extension (see the solution's Going further), but the function returns a single number.
  • Empty input is 0; a one-element array is 1. Every single element is trivially an increasing subsequence of length 1.
Loading editor…