Skip to main content
58

Longest Increasing Subsequence

Mediumdynamic programmingbinary search

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

Given an integer array nums, return the length of its longest strictly increasing subsequence.

Understand the problem

  • A subsequence keeps some of the elements in their original order, but they don't have to be next to each other: [3, 7, 101] is a subsequence of [10, 9, 2, 5, 3, 7, 101, 18]. (Compare a subarray, which must be contiguous.)
  • Strictly increasing means each element is bigger than the one before it. Equal values don't count: [7, 7] isn't increasing.
  • You return only the length, not the subsequence itself.

Example 1

text
Input:  nums = [10, 9, 2, 5, 3, 7, 101, 18]
Output: 4

For example [2, 3, 7, 101] or [2, 5, 7, 18]. There's no increasing subsequence of length 5.

Example 2

text
Input:  nums = [0, 1, 0, 3, 2, 3]
Output: 4

[0, 1, 2, 3].

Example 3

text
Input:  nums = [7, 7, 7, 7]
Output: 1

Equal values aren't strictly increasing, so the best is a single 7.

Constraints

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4

Note

An O(n²) solution passes. Can you get it down to O(n log n)?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Keep, for every possible length, the smallest value an increasing subsequence of that length can end with; each new number either extends the longest one or improves one of those endings, and the number of lengths at the end is the answer.

    The naive approach (and why it's slow)

    Try every subsequence: each element is in or out, so there are 2^n of them. With 2,500 elements, that's impossible.

    Approach 1: O(n²) DP (the easier one to understand)

    Ask a smaller question for each position: what's the longest increasing subsequence that ends at nums[i]? Call it lis[i].

    A subsequence ending at nums[i] either is just [nums[i]] (length 1), or extends one that ends at an earlier, smaller value nums[j]:

    text
    lis[i] = 1 + max(lis[j])   over every j < i with nums[j] < nums[i]
             (or 1 if there's no such j)

    The answer is the largest value in lis. For nums = [10, 9, 2, 5, 3, 7, 101, 18]:

    i01234567
    nums[i]109253710118
    lis[i]11122344

    For example lis[5] = 3: 7 can extend the subsequences ending at 2 (length 1), 5 (length 2) or 3 (length 2), so 1 + 2 = 3. The largest value is 4.

    Two nested loops: O(n²), about 6 million steps for 2,500 elements. That passes.

    Approach 2: O(n log n) with "tails" (used in the reference solution)

    The key insight: among all increasing subsequences of the same length, the one ending with the smallest value is the most useful, because more future numbers can extend it.

    So keep an array tails, where tails[k] = the smallest last value of any increasing subsequence of length k + 1 found so far. tails is always sorted (a longer subsequence has to end with a bigger value), so you can binary search it.

    For each new number x, find the first tail that is >= x:

    • There's none (x is bigger than every tail): x extends the longest subsequence. Append it.
    • Found at position k: x is a smaller ending for length k + 1. Replace tails[k] with x.

    Step by step

    nums = [10, 9, 2, 5, 3, 7, 101, 18]:

    xFirst tail >= xActiontails after
    10noneappend[10]
    910 (position 0)replace[9]
    29 (position 0)replace[2]
    5noneappend[2, 5]
    35 (position 1)replace[2, 3]
    7noneappend[2, 3, 7]
    101noneappend[2, 3, 7, 101]
    18101 (position 3)replace[2, 3, 7, 18]

    Answer: tails.length = 4.

    Careful: tails is not necessarily a real subsequence (it can mix values from different ones). Only its length is guaranteed to be the answer.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Approach 1: O(n²) time, O(n) memory.
    • Approach 2: O(n log n) time (one binary search per element), O(n) memory.

    Common mistakes

    • Allowing equal values. "Strictly increasing" means <, not <=. That's why the binary search looks for the first tail >= x (so an equal value replaces, never appends).
    • Mixing up subsequence and subarray. The elements don't need to be next to each other.
    • Returning lis[n - 1] in approach 1. The longest subsequence doesn't have to end at the last element; take the maximum over all i.
    • Treating tails as the actual answer subsequence.

    Going deeper

    • The tails trick is sometimes called patience sorting, after a card game where you deal cards into piles.
    • Longest Common Subsequence (in 2-D DP) is a different problem with a similar name: it compares two sequences.

    Reference solution

    js
    /**
     * @param {number[]} nums
     * @return {number}
     */
    export default function lengthOfLis(nums) {
      // tails[k] = the smallest last value of any increasing subsequence of length k + 1.
      // It's always sorted, so we can binary search it.
      const tails = []
      for (const x of nums) {
        // Binary search for the first tail >= x (tails.length if there's none).
        let lo = 0
        let hi = tails.length
        while (lo < hi) {
          const mid = (lo + hi) >> 1
          if (tails[mid] < x) lo = mid + 1
          else hi = mid
        }
        // lo === tails.length: x extends the longest subsequence (this appends).
        // Otherwise: x is a smaller ending for length lo + 1, so it replaces that tail.
        tails[lo] = x
      }
      return tails.length // tails isn't a real subsequence, but its length is the answer
    }
    ts
    export default function lengthOfLis(nums: number[]): number {
      // tails[k] = the smallest last value of any increasing subsequence of length k + 1.
      // It's always sorted, so we can binary search it.
      const tails: number[] = []
      for (const x of nums) {
        // Binary search for the first tail >= x (tails.length if there's none).
        let lo = 0
        let hi = tails.length
        while (lo < hi) {
          const mid = (lo + hi) >> 1
          if (tails[mid] < x) lo = mid + 1
          else hi = mid
        }
        // lo === tails.length: x extends the longest subsequence (this appends).
        // Otherwise: x is a smaller ending for length lo + 1, so it replaces that tail.
        tails[lo] = x
      }
      return tails.length // tails isn't a real subsequence, but its length is the answer
    }
    python
    from bisect import bisect_left
    
    
    def length_of_lis(nums: list[int]) -> int:
        # tails[k] = the smallest last value of any increasing subsequence of length k + 1.
        # It's always sorted, so we can binary search it.
        tails = []
        for x in nums:
            k = bisect_left(tails, x)  # position of the first tail >= x
            if k == len(tails):
                tails.append(x)  # x extends the longest subsequence
            else:
                tails[k] = x  # a smaller ending for length k + 1
        return len(tails)  # tails isn't a real subsequence, but its length is the answer