Longest increasing subsequence

The longest run of values that keeps rising, where you may skip elements but not reorder them.

Time O(n log n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

tails[k] is the smallest value that can end an increasing subsequence of length k + 1. tails stays sorted, so binary search finds where each new value goes: past the end means a longer subsequence; otherwise it replaces a bigger tail, keeping that length open to more values.

Code

public static int LengthOfLis(int[] a) {
    var tails = new List<int>();
    foreach (int x in a) {
        int lo = 0, hi = tails.Count;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (tails[mid] < x) lo = mid + 1; else hi = mid;
        }
        if (lo == tails.Count) tails.Add(x);
        else tails[lo] = x;
    }
    return tails.Count;
}
static int lengthOfLis(int[] a) {
    List<Integer> tails = new ArrayList<>();
    for (int x : a) {
        int lo = 0, hi = tails.size();
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (tails.get(mid) < x) lo = mid + 1; else hi = mid;
        }
        if (lo == tails.size()) tails.add(x);
        else tails.set(lo, x);
    }
    return tails.size();
}
int lengthOfLis(const vector<int>& a) {
    vector<int> tails;
    for (int x : a) {
        int lo = 0, hi = tails.size();
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (tails[mid] < x) lo = mid + 1; else hi = mid;
        }
        if (lo == (int)tails.size()) tails.push_back(x);
        else tails[lo] = x;
    }
    return tails.size();
}
def length_of_lis(a: list[int]) -> int:
    tails = []
    for x in a:
        lo, hi = 0, len(tails)
        while lo < hi:
            mid = (lo + hi) // 2
            if tails[mid] < x: lo = mid + 1
            else: hi = mid
        if lo == len(tails): tails.append(x)
        else: tails[lo] = x
    return len(tails)

Tips

In the .NET library

List<T>.BinarySearch returns the bitwise complement of the insert position when the value is missing: ~index.