Longest increasing subsequence
The longest run of values that keeps rising, where you may skip elements but not reorder them.
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
- tails is not the subsequence itself, only its length is the answer.
- Use "first tail ≥ x" (lower bound) for strictly increasing; "first tail > x" allows equal values.
- The O(n²) version keeps dp[i] = length ending at i and checks every earlier j.
In the .NET library
List<T>.BinarySearch returns the bitwise complement of the insert position when the value is missing: ~index.