← Back to Algorithms, page 2

algorithms-0033 · Hard senior

Longest increasing subsequence: find the length of the longest strictly increasing subsequence in O(n log n).

The O(n^2) DP sets best[i] = 1 + max(best[j]) over earlier smaller values. The O(n log n) method keeps tails[k], the smallest possible last value of an increasing subsequence of length k + 1. For each value, binary search the first tail at least as large and replace it, or append if none exists. The length of tails is the answer; tails itself is not necessarily a real subsequence.

Full answer

Problem

Given nums, return the length of the longest strictly increasing subsequence (not necessarily contiguous).

Example: [10, 9, 2, 5, 3, 7, 101, 18] gives 4 ([2, 3, 7, 18] is one answer).

Constraints: 0 <= len(nums) <= 2500 (the O(n log n) method scales to 10^5 and more).

Brute force

Try all 2^n subsequences: exponential.

Better: O(n^2) DP

best[i] = length of the longest increasing subsequence ending at i = 1 + max(best[j] for j < i if nums[j] < nums[i]), or 1. The answer is max(best). This is easy to explain and is the reference in the test.

Optimal approach

Keep tails, where tails[k] is the smallest tail of any increasing subsequence of length k + 1 found so far. For each x:

  1. i = bisect_left(tails, x), the first tail at least x.
  2. If i == len(tails), append x (a longer subsequence exists).
  3. Otherwise set tails[i] = x (a length i + 1 subsequence can now end lower).

Why it works

tails is always strictly increasing: a subsequence of length k + 1 contains one of length k with a smaller tail. A smaller tail is never worse, because it leaves more room for future values. When x arrives, it can extend every subsequence whose tail is less than x; the longest of those has length i, so x becomes the best tail for length i + 1. Using bisect_left makes the subsequence strictly increasing; bisect_right would allow equal values (non-decreasing).

The final tails is not always an actual subsequence. To reconstruct one, also store, for each position, the index of its predecessor.

Complexity

O(n log n) time, O(n) space. The DP version is O(n^2) time.

Code

python
from bisect import bisect_left


def length_of_lis(nums):
    """Length of the longest strictly increasing subsequence. O(n log n).

    tails[k] = smallest possible tail of an increasing subsequence of length k + 1.
    """
    tails = []
    for x in nums:
        i = bisect_left(tails, x)       # first tail >= x
        if i == len(tails):
            tails.append(x)             # x extends the longest subsequence
        else:
            tails[i] = x                # x is a smaller tail for length i + 1
    return len(tails)


def length_of_lis_dp(nums):
    """O(n^2) dynamic programming reference."""
    best = [1] * len(nums)
    for i in range(len(nums)):
        for j in range(i):
            if nums[j] < nums[i]:
                best[i] = max(best[i], best[j] + 1)
    return max(best, default=0)


if __name__ == "__main__":
    for f in (length_of_lis, length_of_lis_dp):
        assert f([10, 9, 2, 5, 3, 7, 101, 18]) == 4
        assert f([0, 1, 0, 3, 2, 3]) == 4
        assert f([7, 7, 7, 7]) == 1          # strictly increasing
        assert f([]) == 0
        assert f([5]) == 1
        assert f([1, 2, 3, 4]) == 4
        assert f([4, 3, 2, 1]) == 1
    print("all tests passed")

Save as a33_lis.py and run python3 a33_lis.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list returns 0. All equal values returns 1 (strictly increasing). Already sorted returns n. Strictly decreasing returns 1. Negative numbers work the same way.

Pattern

DP with a monotonic auxiliary array searched by binary search (patience sorting). Related: Russian doll envelopes (sort, then LIS), longest chain of pairs, and minimum deletions to make a list sorted.

python
from bisect import bisect_left


def length_of_lis(nums):
    """Length of the longest strictly increasing subsequence. O(n log n).

    tails[k] = smallest possible tail of an increasing subsequence of length k + 1.
    """
    tails = []
    for x in nums:
        i = bisect_left(tails, x)       # first tail >= x
        if i == len(tails):
            tails.append(x)             # x extends the longest subsequence
        else:
            tails[i] = x                # x is a smaller tail for length i + 1
    return len(tails)


def length_of_lis_dp(nums):
    """O(n^2) dynamic programming reference."""
    best = [1] * len(nums)
    for i in range(len(nums)):
        for j in range(i):
            if nums[j] < nums[i]:
                best[i] = max(best[i], best[j] + 1)
    return max(best, default=0)


if __name__ == "__main__":
    for f in (length_of_lis, length_of_lis_dp):
        assert f([10, 9, 2, 5, 3, 7, 101, 18]) == 4
        assert f([0, 1, 0, 3, 2, 3]) == 4
        assert f([7, 7, 7, 7]) == 1          # strictly increasing
        assert f([]) == 0
        assert f([5]) == 1
        assert f([1, 2, 3, 4]) == 4
        assert f([4, 3, 2, 1]) == 1
    print("all tests passed")

tails array with bisect_left plus an O(n^2) DP reference; both pass the same tests.

Complexity

Time: O(n log n). Space: O(n). The DP version is O(n^2) and is used as a reference.

By level

Fresher: Writes the O(n^2) DP with the recurrence and traces the example. Should test a list of equal values.

Mid: Implements the tails method, explains why tails stays sorted and handles strictness. Explains the choice between bisect_left and bisect_right.

Senior: Reconstructs the sequence with predecessor links, solves envelope variants and relates it to patience sorting and the Erdos-Szekeres bound. Explains how to rebuild the actual subsequence.

Key points

  • tails[k] is the smallest tail of a length k + 1 increasing subsequence
  • tails stays sorted, so binary search works
  • Replace the first tail >= x, or append
  • bisect_left for strict, bisect_right for non-decreasing
  • tails is not the subsequence itself

Common mistakes

  • Returning tails as the answer subsequence
  • Using bisect_right for a strictly increasing requirement
  • Confusing subsequence with subarray
  • Not explaining why a smaller tail is better

Follow-ups

  • How would you reconstruct the subsequence?
  • How do you solve Russian doll envelopes?
  • What changes for non-decreasing subsequences?

Tips

  • Give the O(n^2) DP first
  • Explain the tails invariant in one sentence
  • Test equal values

Evaluation rubric

  • Correct DP recurrence
  • Correct O(n log n) method
  • Strict versus non-strict handled
  • Correct complexity