Skip to content
Problem 300 · LeetCode 300(opens in a new tab)

Longest Increasing Subsequence

MediumArrays

You are given a list of whole numbers, nums. A subsequence keeps some of the numbers, in their original order, and drops the rest. It does not have to be contiguous.

Return the length of the longest subsequence whose numbers go strictly up: each one larger than the one before it. Equal neighbours do not count as going up.

Example 1

Input:  nums = [4, 10, 3, 8, 9, 2]
Output: 3
Why:    4, 8, 9 (or 3, 8, 9) goes up; nothing longer does
2 more examples and the constraints

Example 2

Input:  nums = [5, 5, 5]
Output: 1
Why:    equal numbers do not go strictly up

Example 3

Input:  nums = [-2, 0, 7, 1, 3, 4]
Output: 5
Why:    skip the 7: -2, 0, 1, 3, 4

Constraints

  • 1 ≤ length of nums ≤ 2,500
  • −10,000 ≤ nums[i] ≤ 10,000
  • Follow-up: can you do it in O(n log n) time?

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP over every earlier numberO(n²)
  2. Smallest tails + binary searchO(n log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 2,500 numbersVerdict
DP over every earlier numberO(n²)
Passes; easy to explain
Smallest tails + binary searchO(n log n)
Best; answers the follow-up

n = how many numbers are in the list.

Edge cases to test

  • One number. [42] gives 1.
  • All equal. [5, 5, 5] gives 1: strictly up means equal values cannot share a run.
  • Strictly falling. [9, 7, 5, 3] gives 1; every number replaces the only tail.
  • The best run starts late. [10, 11, 1, 2, 3, 4] gives 4, not the 2 from the start.

Common mistakes

  • Searching for the first tail > x instead of ≥ x, which lets equal numbers extend a run.
  • Returning dp[n − 1] instead of the largest dp value; the best run may end anywhere.
  • Reading tails as the subsequence itself. Only its length is the answer.

How to talk through it

  1. 1Clarify. Strictly increasing or non-decreasing? Do I return the length or the subsequence? Can the list be empty?
  2. 2Give the O(n²) DP. dp[i] is the longest run ending at i, built from smaller numbers before it.
  3. 3Ask what is worth keeping. For each length, only the smallest possible end matters, and those ends stay sorted.
  4. 4Code the binary search. Find the first tail ≥ x; append or replace. Say why the list stays sorted.
  5. 5Test out loud. Run the all-equal case and a falling list before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?