Longest Increasing Subsequence

Medium Dynamic ProgrammingBinary Search

Problem

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

Example 1 Input: nums = [10,9,2,5,3,7,101,18] Output: 4
Example 2 Input: nums = [0,1,0,3,2,3] Output: 4
Example 3 Input: nums = [7,7,7,7] Output: 1

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

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)

Java

import java.util.Arrays;

class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] tails = new int[nums.length];
        int len = 0;
        for (int x : nums) {
            int i = Arrays.binarySearch(tails, 0, len, x);
            if (i < 0) i = -i - 1;
            tails[i] = x;
            if (i == len) len++;
        }
        return len;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Longest Increasing Subsequence interactively → ← All solutions