Skip to content
DSA Patterns
Menu
Language
One-Dimensional DPLC #3005 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Longest Increasing Subsequence

Problem (restated)

Return length of the longest strictly increasing subsequence.

Intuition

Maintain smallest tail of all increasing subsequences of each length; binary search place for each num.

Approaches

Patience sorting (tails)

Unverified
Time O(n log n)Space O(n)

Idea. tails[len-1] = smallest tail for length len; lower_bound replace or append.

Walkthrough. [10,9,2,5,3,7,101,18] → length 4 (2,3,7,101).

Trade-offs. O(n²) DP is simpler; patience is faster.

Solution
export function lengthOfLIS(nums: number[]): number {
  const tails: number[] = [];
  for (const x of nums) {
    let lo = 0, hi = tails.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (tails[mid]! < x) lo = mid + 1;
      else hi = mid;
    }
    if (lo === tails.length) tails.push(x);
    else tails[lo] = x;
  }
  return tails.length;
}
export function lengthOfLIS(nums: number[]): number {
  const tails: number[] = [];
  for (const x of nums) {
    let lo = 0, hi = tails.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (tails[mid]! < x) lo = mid + 1;
      else hi = mid;
    }
    if (lo === tails.length) tails.push(x);
    else tails[lo] = x;
  }
  return tails.length;
}

Template connection

tails holds the smallest tail of each length built so far. Binary search replaces a tail or appends one. The number of tails is the LIS length.

Reflection

  • tails stores the smallest tail of every length. A new value replaces one tail or extends the array. The answer is the length, not the values.
  • The sequence is strictly increasing, so an equal value does not extend a tail. A decreasing array answers 1.
  • tails is not the subsequence. The O(n²) DP returns the same length. This pass is O(n log n).
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

LIS of [10,9,2,5,3,7,101,18]. Patience piles: tails[len] = smallest tail of an LIS of that length.

10
0
9
1
2
2
5
3
3
4
7
5
101
6
18
7

tails = []

Key:Active rangeMatchSettledEliminated