Video in progress

Strong Middle 🧠 Problem solving

How do you find the length of the longest strictly increasing subsequence (LIS) of an array in O(n log n)?

I keep a tails array: tails[k] is the smallest last element among increasing subsequences of length k + 1. For each new number I find its place with binary search and either replace an entry or append at the end. The answer is the filled length of tails.

📖 Answer

[10, 9, 2, 5, 3, 7, 101, 18] → the answer is 4 (for example 2, 3, 7, 18).

The classic DP is dp[i] = 1 + max(dp[j]) with j < i and a[j] < a[i]. It's O(n²): for 10⁵ elements that's 10¹⁰ operations, which won't finish in time.

static int lis(int[] a) {
    int[] tails = new int[a.length];
    int len = 0;
    for (int x : a) {
        int pos = Arrays.binarySearch(tails, 0, len, x);
        if (pos < 0) pos = -pos - 1;          // the insertion point
        tails[pos] = x;
        if (pos == len) len++;
    }
    return len;
}

Why does it work? tails is always strictly increasing. Among subsequences of the same length, the one with the smaller last element is better, because more numbers can attach to it later. That's why we replace a larger ending with a smaller one.

Here's the part that confuses people: tails itself is not the LIS. For example, after [3, 4, 1] it becomes [1, 4], but that sequence doesn't exist in the array. If you need the sequence itself, you store a parent index for each element and walk backward from the end.

When Arrays.binarySearch finds an equal element, it returns its index, and replacing at that spot is exactly right for strict increase. If you need the "non-decreasing" variant (equality allowed), you search for the first strictly greater element (the upper bound), and binarySearch doesn't give you that; you write it yourself.

Related problems: "Russian doll envelopes" means sorting by one dimension and then doing LIS on the other. Patience diff also uses this same patience-sorting idea on unique lines.