progress

~/problems / 1-D dynamic programming / Longest increasing subsequence

Longest Increasing Subsequence

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write length_of_lis(nums: list[int]) -> int: the length of the longest strictly increasing subsequence of nums (elements kept in order, not necessarily adjacent).

Examples:

  • length_of_lis([4, 1, 5, 2, 6, 3, 7]) == 4 (e.g. 1, 2, 3, 7)
  • length_of_lis([5, 5, 5]) == 1 (equal values don't count as increasing)
  • length_of_lis([9, 7, 4]) == 1

Constraints: 1 <= len(nums) <= 100_000, values fit in 32-bit ints (may be negative).

The O(n²) DP is the usual first answer.

⭐ Bonus: a speed test with 100,000 elements earns a star in O(n log n).

Show hint

for each length k, keep the smallest value that an increasing subsequence of length k can end with. That list stays sorted, so each new number can find its place in it by binary search.

Topic: Longest increasing subsequence. O(n log n) with tails[] + bisect; rebuild via parent pointers.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc