Longest Increasing Subsequence

Medium

Topics
ArrayBinary SearchDynamic Programming

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

Example 1

10091225334751016187
one longest increasing subsequence
The shaded cells increase left to right but need not be adjacent — that is what separates a subsequence from a subarray. Length 4.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: [2,3,7,101] or [2,3,7,18].

Example 2

001102332435
one longest increasing subsequence
Input:  nums = [0,1,0,3,2,3]
Output: 4

Constraints

  • 1 <= nums.length <= 2500
  • -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

The O(n²) DP tries every previous element. The faster idea: keep an array tails where tails[k] is the smallest tail value of any increasing subsequence of length k+1.

A smaller tail is always at least as useful (it leaves more room to extend), so binary-searching each number into tails keeps it sorted, and its length is the LIS length. This is patience sorting.

Approach

  1. For each number, binary-search the first tail ≥ it.
  2. If none is ≥ it, it extends the longest run → append.
  3. Otherwise replace that tail with this (smaller) value.
  4. The length of tails is the answer.

Walkthrough

nums = [10, 9, 2, 5, 3, 7]
10 -> [10]
9  -> [9]
2  -> [2]
5  -> [2,5]
3  -> [2,3]
7  -> [2,3,7]  -> length 3

Complexity

  • Time — O(n log n): one binary search per element.
  • Space — O(n): the tails array.

Common Pitfalls

  • tails is not itself a valid subsequence — only its length is meaningful.
  • Use bisect_left for strictly increasing; bisect_right would allow duplicates.
  • mid = (lo + hi) / 2 is the textbook form, and in Java or C++ it is the one that bites: the moment lo + hi passes 2^31 - 1 it wraps negative and the index flies out of range. This problem’s bounds never get close, so the code above is correct as written, but lo + (hi - lo) / 2 is the habit worth keeping — same answer, same cost, no overflow. Python’s integers are arbitrary precision, so it is a non-issue there.

Full Solution — all languages

class Solution:
    def lengthOfLIS(self, nums):
        import bisect
        tails = []
        for x in nums:
            i = bisect.bisect_left(tails, x)
            if i == len(tails):
                tails.append(x)
            else:
                tails[i] = x
        return len(tails)
SensAI
Beta
Tap the mic to stop voice mode