Longest Increasing Subsequence

Pattern: LIS family

medium

Keep tails[k], the smallest last value of any increasing run of length k + 1 seen so far. Each new value replaces the first tail that is at least it, or extends the list; the list's length is the answer, found in O(n log n).

The problem

Return the length of the longest strictly increasing subsequence of nums.

Think first

  • What is the O(n²) DP state?
  • Why keep the smallest possible tail for each length?
  • How do you find where a value goes?

Hints

    Brute force, and why it fails

    For each index, look at every earlier smaller value: O(n²). It is correct and a good first answer.

    The key insight

    Only the best tail for each length matters, and those tails are sorted, so each value needs one binary search.

    Dry run

    tails2

    [10, 9, 2, 5, 3, 7, 101, 18]. 10, then 9 replaces it, then 2 replaces it.

    Step 1 of 3

    The plan

    tails = []
    for x: k = first index with tails[k] >= x
      if k == len(tails): append x else tails[k] = x
    return len(tails)
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    One binary search per value.

    Edge cases

    • One value: 1.
    • All equal: 1 (strictly increasing).
    • Already sorted: n.
    I've built my logic, show the code

    Java

    class Solution {
        public int lengthOfLIS(int[] nums) {
            int[] tails = new int[nums.length];     // tails[k]: the smallest possible last value of an increasing run of length k + 1
            int size = 0;
            for (int x : nums) {
                int lo = 0, hi = size;              // the first tail that is >= x
                while (lo < hi) {
                    int mid = (lo + hi) / 2;
                    if (tails[mid] < x) lo = mid + 1; else hi = mid;
                }
                tails[lo] = x;                      // x extends the run before it, or improves an existing tail
                if (lo == size) size++;
            }
            return size;
        }
    }

    C++

    class Solution {
    public:
        int lengthOfLIS(vector<int>& nums) {
            vector<int> tails;                      // tails[k]: the smallest possible last value of an increasing run of length k + 1
            for (int x : nums) {
                auto it = lower_bound(tails.begin(), tails.end(), x);   // the first tail that is >= x
                if (it == tails.end()) tails.push_back(x);              // x extends the longest run
                else *it = x;                                           // or improves an existing tail
            }
            return static_cast<int>(tails.size());
        }
    };

    Python

    import bisect
    
    class Solution:
        def lengthOfLIS(self, nums: list[int]) -> int:
            tails = []                              # tails[k]: the smallest last value of an increasing run of length k + 1
            for x in nums:
                k = bisect.bisect_left(tails, x)    # the first tail that is >= x
                if k == len(tails):
                    tails.append(x)                 # x extends the longest run
                else:
                    tails[k] = x                    # or improves an existing tail
            return len(tails)

    Common mistakes

    • Using the first tail greater than x, which allows equal values.
    • Thinking tails is itself a valid LIS.

    Similar problems