SDE & MLE Prep

300. Longest Increasing Subsequence

Problem

Return the length of the longest strictly increasing subsequence of nums (elements in order, not necessarily adjacent).

Example: [10,9,2,5,3,7,101,18] → 4 (e.g. 2, 3, 7, 101)

Constraints: n ≤ 2500. Follow-up: O(n log n).

O(n²): dp[i] = 1 + max(dp[j]) for j < i, nums[j] < nums[i]. O(n log n): tails[k] = smallest tail of an increasing subsequence of length k+1; binary-search each number's position and overwrite.

nums  10 9 2 5 3 7 101 18
tails [10] -> [9] -> [2] -> [2,5] -> [2,3] -> [2,3,7] -> [2,3,7,101] -> [2,3,7,18]   len 4

Complexity: O(n log n).

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        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)