download

Longest increasing subsequence: from O(n²) to O(n log n)

Algorithms~25 minReviewed 1 Nov 2026Free · No sign-in

Question

A shop records an item's price each week: [4, 9, 5, 2, 7, 3, 8, 1]. Find the length of the longest strictly increasing subsequence. A subsequence keeps the original order but may skip items. Here the answer is 4: 4, 5, 7, 8. First describe an O(n²) solution. Then write one that runs in O(n log n).

"PYTHON"
lis_length([4, 9, 5, 2, 7, 3, 8, 1])  # 4
lis_length([4, 4, 4])                 # 1, equal is not increasing
lis_length([])                        # 0
"CODE · PYTHON"
def lis_length(nums):
    ...
Show hints (3)
  1. "A SMALLER QUESTION"

    For each index i, what is the longest increasing subsequence that ends exactly at nums[i]? It extends one that ends earlier, at a smaller value.

  2. "WHAT TO REMEMBER"

    For the fast version, keep one number per length: the smallest value that an increasing subsequence of that length can end with. A smaller end leaves more room for later numbers.

  3. "WHERE IT GOES"

    That list stays sorted. For each x, bisect_left finds the first value that is >= x. Replace that value with x, or append x if it is bigger than all of them.

Show checked explanation

In O(n²), find for each item the longest increasing subsequence that ends at it. It extends the best one that ends at an earlier, smaller item. In O(n log n), keep tails: tails[k] is the smallest last value of an increasing subsequence of length k + 1. Place each number with a binary search. The answer is len(tails).

"SOLUTION · PYTHON"
from bisect import bisect_left


def lis_length(nums):
    # tails[k]: smallest end of an increasing subsequence of length k + 1
    tails = []
    for x in nums:
        i = bisect_left(tails, x)
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)


print(lis_length([4, 9, 5, 2, 7, 3, 8, 1]))
print(lis_length([4, 4, 4]))
print(lis_length([]))
"OUTPUT"
4
1
0

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Start with the O(n²) version. best[i] is the length of the longest increasing subsequence that ends at nums[i]. It is 1 more than the largest best[j] with j < i and nums[j] < nums[i], or 1 if there is no such j:

"PYTHON"
def lis_quadratic(nums):
    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)

For the prices, best is [1, 2, 2, 1, 3, 2, 4, 1]. The answer is the largest value, 4, which ends at the price 8.

The fast version keeps tails. For each price, bisect_left finds the first tail that is greater than or equal to it:

pricesteptails
4append[4]
9append[4, 9]
5replace 9[4, 5]
2replace 4[2, 5]
7append[2, 5, 7]
3replace 5[2, 3, 7]
8append[2, 3, 7, 8]
1replace 2[1, 3, 7, 8]

Why replace? After 4, 9 and 5, both 4, 9 and 4, 5 have length 2. Ending at 5 is better, because more later prices can extend it. A replace never changes the length of tails. The new value is bigger than the tail before it and no bigger than the one it replaces, so tails stays sorted. Its length always equals the longest length found so far. Each price costs one binary search, so the total is O(n log n).

The final tails is [1, 3, 7, 8]. That is not a real subsequence, because 1 is the last price. Only its length is the answer.

Common mistakes

  • Returning tails as the subsequence. For the prices it is [1, 3, 7, 8], but 1 comes after 8 in the input.
  • Using bisect_right for a strictly increasing subsequence. Equal values then extend the subsequence, so [4, 4, 4] gives 3 instead of 1.
  • Returning best[-1] instead of max(best) in the O(n²) version. The best subsequence need not end at the last item. For the prices, best[-1] is 1, but the answer is 4.
  • Taking each price that beats the last one you took. That greedy rule takes 4, then 9, and gets stuck at length 2.

Follow-up questions

  • "Return one longest subsequence, not only its length." Store indexes in tails instead of values, and search with bisect_left(tails, x, key=nums.__getitem__). When you place an item, also save the index stored in the slot to its left: that is the item before it. At the end, start from the last slot and follow these links back. For the prices you get 4, 5, 7, 8. It is still O(n log n).
  • "What if equal values are allowed, so 4, 4, 4 has length 3?" That is the longest non-decreasing subsequence. Use bisect_right, so an equal value goes after the tails that match it and can extend the subsequence. [4, 4, 4] then gives 3.
  • "How many longest increasing subsequences are there?" Extend the O(n²) version with count[i], the number of longest subsequences that end at i. When best[j] + 1 beats best[i], copy count[j]. When it ties, add count[j]. The prices have just one, but [2, 6, 4, 9] has two: 2, 6, 9 and 2, 4, 9.

What a strong answer covers

Defines the O(n²) state in words. Explains what tails[k] means and why a replace keeps it sorted. Says the final tails is not a real subsequence, and picks bisect_left or bisect_right on purpose.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Coding Interview Patterns (Alex Xu and Shaun Gunawardane, 2024); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.