cswork / templatesOpen the Line 500 list

STOP 25 · DYNAMIC PROGRAMMING

Subsequences and Partial Orders

LIS with a tails array and binary search O(n log n)

Contest ratings Rating 1597–Rating 2027· median Rating 1835(6 of 11 problems rated by zerotrac)

Open the Line 500 list · stop 25 · 11 problems
Learn first
Leads to
How often asked
asked by 2 companies · in 2 reportsExperian 1, TikTok / ByteDance 1

Warm up with this one

LC 300Longest Increasing SubsequenceMedium
Stuck? Peek at the approach

Build the quadratic DP first, then explain why minimum tail values with binary search recover the optimal length.

Key points

  1. tails[k] is the smallest possible tail of an increasing subsequence of length k+1; it is itself sorted, so you can binary search it.
  2. Strictly increasing uses lower_bound (first ≥ x); non-decreasing uses upper_bound (first > x).
  3. For 2-D nesting such as envelopes, sort by width ascending and by height descending on ties, then run LIS on the heights.

Common pitfalls

  • tails is not an actual longest subsequence, only its length is right; record predecessors if you must output one.
  • Using the wrong bound for strict versus non-strict is off by one or more on inputs with many duplicates.
  • Counting how many longest subsequences there are needs the O(n²) dp with a count array.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

2D DP · filling the LCS table

Longest common subsequence of "ACBD" and "ABCD"

Try your own input
∅
A
B
C
D
∅
00,0
00,1
00,2
00,3
00,4
A
01,0
·1,1
·1,2
·1,3
·1,4
C
02,0
·2,1
·2,2
·2,3
·2,4
B
03,0
·3,1
·3,2
·3,3
·3,4
D
04,0
·4,1
·4,2
·4,3
·4,4
CurrentDiscovered / computedAnswer
LCS length
—

dp[i][j] is the LCS length of the first i characters of "ACBD" and the first j of "ABCD". Row 0 and column 0 are empty strings: all 0.

InvariantRows fill left to right: when dp[i][j] is computed, the cells above, left and top-left are already final.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 300, with it.

Python
from bisect import bisect_left


def lis_length(nums: list[int]) -> int:
    """Length of the longest strictly increasing subsequence."""
    tails = []  # tails[k]: smallest tail of an increasing subsequence of length k+1
    for x in nums:
        i = bisect_left(tails, x)  # bisect_right for non-decreasing
        if i == len(tails):
            tails.append(x)
        else:
            tails[i] = x
    return len(tails)
C++
// Length of the longest strictly increasing subsequence.
int lisLength(const vector<int>& nums) {
    vector<int> tails;  // tails[k]: smallest tail of an increasing subsequence of length k+1
    for (int x : nums) {
        auto it = lower_bound(tails.begin(), tails.end(), x);  // upper_bound for non-decreasing
        if (it == tails.end()) tails.push_back(x);
        else *it = x;
    }
    return tails.size();
}
Java
class Solution {
    // Length of the longest strictly increasing subsequence.
    int lisLength(int[] nums) {
        int[] tails = new int[nums.length]; // tails[k]: smallest tail of length k+1
        int len = 0;
        for (int x : nums) {
            int lo = 0, hi = len; // first index with tails[i] >= x (use > for non-decreasing)
            while (lo < hi) {
                int mid = (lo + hi) >>> 1;
                if (tails[mid] >= x) hi = mid;
                else lo = mid + 1;
            }
            tails[lo] = x;
            if (lo == len) len++;
        }
        return len;
    }
}
Go
import "sort"

// lisLength returns the length of the longest strictly increasing subsequence.
func lisLength(nums []int) int {
	var tails []int // tails[k]: smallest tail of an increasing subsequence of length k+1
	for _, x := range nums {
		i := sort.SearchInts(tails, x) // first index with tails[i] >= x
		if i == len(tails) {
			tails = append(tails, x)
		} else {
			tails[i] = x
		}
	}
	return len(tails)
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

O(n²) LIS that tracks length and countO(n²) time · O(n) space

When the count of longest increasing subsequences, or an actual sequence, is needed, the tails array is not enough, so fall back to O(n²): length[i] is the longest ending at i and count[i] how many there are; a longer one takes over the count, an equally long one adds to it. LC 673 (Number of Longest Increasing Subsequence); LC 368, LC 1048 and LC 646 use the same double loop.

Python
def count_lis(nums: list[int]) -> int:
    """Number of longest strictly increasing subsequences (LC 673)."""
    n = len(nums)
    length = [1] * n  # length[i]: longest increasing subsequence ending at i
    count = [1] * n  # count[i]: how many of that length end at i
    for i in range(n):
        for j in range(i):
            if nums[j] < nums[i]:
                if length[j] + 1 > length[i]:  # longer: take over j's count
                    length[i], count[i] = length[j] + 1, count[j]
                elif length[j] + 1 == length[i]:  # as long: add j's count
                    count[i] += count[j]
    best = max(length)
    return sum(c for l, c in zip(length, count) if l == best)
C++
// Number of longest strictly increasing subsequences (LC 673).
long long countLis(const vector<int>& nums) {
    int n = nums.size();
    vector<int> length(n, 1);  // length[i]: longest increasing subsequence ending at i
    vector<long long> count(n, 1);  // count[i]: how many of that length end at i
    for (int i = 0; i < n; i++)
        for (int j = 0; j < i; j++) {
            if (nums[j] >= nums[i]) continue;
            if (length[j] + 1 > length[i]) {  // longer: take over j's count
                length[i] = length[j] + 1;
                count[i] = count[j];
            } else if (length[j] + 1 == length[i]) {  // as long: add j's count
                count[i] += count[j];
            }
        }
    int best = *max_element(length.begin(), length.end());
    long long total = 0;
    for (int i = 0; i < n; i++)
        if (length[i] == best) total += count[i];
    return total;
}
Java
class Solution {
    // Number of longest strictly increasing subsequences (LC 673).
    long countLis(int[] nums) {
        int n = nums.length, best = 0;
        int[] length = new int[n]; // length[i]: longest increasing subsequence ending at i
        long[] count = new long[n]; // count[i]: how many of that length end at i
        for (int i = 0; i < n; i++) {
            length[i] = 1;
            count[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[j] >= nums[i]) continue;
                if (length[j] + 1 > length[i]) { // longer: take over j's count
                    length[i] = length[j] + 1;
                    count[i] = count[j];
                } else if (length[j] + 1 == length[i]) { // as long: add j's count
                    count[i] += count[j];
                }
            }
            best = Math.max(best, length[i]);
        }
        long total = 0;
        for (int i = 0; i < n; i++)
            if (length[i] == best) total += count[i];
        return total;
    }
}
Go
// countLis returns the number of longest strictly increasing subsequences (LC 673).
func countLis(nums []int) int {
	n := len(nums)
	length, count := make([]int, n), make([]int, n) // longest ending at i, and how many of that length
	best := 0
	for i := range nums {
		length[i], count[i] = 1, 1
		for j := 0; j < i; j++ {
			if nums[j] >= nums[i] {
				continue
			}
			if length[j]+1 > length[i] { // longer: take over j's count
				length[i], count[i] = length[j]+1, count[j]
			} else if length[j]+1 == length[i] { // as long: add j's count
				count[i] += count[j]
			}
		}
		best = max(best, length[i])
	}
	total := 0
	for i := range nums {
		if length[i] == best {
			total += count[i]
		}
	}
	return total
}
DP keyed by value: a hash map instead of indexesO(n) time · O(n) space

When neighbours in a subsequence are tied by value (a fixed common difference, Fibonacci-like steps), store states in a hash map keyed by value: the longest ending in x is one more than the longest ending in x - d, one pass, O(n). LC 1218 (Longest Arithmetic Subsequence of Given Difference); LC 1027 and LC 873 put the difference or the previous term into the key as well.

Python
def longest_arith_subseq(arr: list[int], difference: int) -> int:
    """Longest subsequence whose neighbours differ by exactly difference (LC 1218)."""
    best_end: dict[int, int] = {}  # value -> longest such subsequence ending with that value
    best = 0
    for x in arr:
        best_end[x] = best_end.get(x - difference, 0) + 1  # extend the one ending at x - difference
        best = max(best, best_end[x])
    return best
C++
// Longest subsequence whose neighbours differ by exactly difference (LC 1218).
int longestArithSubseq(const vector<int>& arr, int difference) {
    unordered_map<int, int> bestEnd;  // value -> longest such subsequence ending with that value
    int best = 0;
    for (int x : arr) {
        auto it = bestEnd.find(x - difference);
        int len = (it == bestEnd.end() ? 0 : it->second) + 1;  // extend the one ending at x - difference
        bestEnd[x] = len;
        best = max(best, len);
    }
    return best;
}
Java
class Solution {
    // Longest subsequence whose neighbours differ by exactly difference (LC 1218).
    int longestArithSubseq(int[] arr, int difference) {
        Map<Integer, Integer> bestEnd = new HashMap<>(); // value -> longest such subsequence ending with that value
        int best = 0;
        for (int x : arr) {
            int len = bestEnd.getOrDefault(x - difference, 0) + 1; // extend the one ending at x - difference
            bestEnd.put(x, len);
            best = Math.max(best, len);
        }
        return best;
    }
}
Go
// longestArithSubseq returns the longest subsequence whose neighbours differ by exactly difference.
func longestArithSubseq(arr []int, difference int) int {
	bestEnd := map[int]int{} // value -> longest such subsequence ending with that value
	best := 0
	for _, x := range arr {
		bestEnd[x] = bestEnd[x-difference] + 1 // extend the one ending at x - difference
		best = max(best, bestEnd[x])
	}
	return best
}

Why it works

  1. tails is strictly increasing: drop the last element of an increasing subsequence of length k+1 and you get one of length k with a smaller end, so tails[k] < tails[k+1], which allows binary search.
  2. Replacing the first entry ≥ x with x only lowers the smallest end for one length and never changes the longest length reached; a smaller end is easier to extend later, so this greedy never makes the answer worse.
  3. tails is usually not an actual subsequence; only its length is the answer, and printing the sequence needs predecessor links on the side.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
最长递增子序列我用 O(n log n) 的做法:维护 tails,tails[k] 是长度为 k+1 的递增子序列可能的最小结尾。它本身递增,所以每来一个数就二分找第一个大于等于它的位置替换,找不到就追加。结尾越小越容易被后面接上,所以替换不会让答案变差,最后 tails 的长度就是答案。要求非严格递增时把 lower_bound 换成 upper_bound。
English
For the longest increasing subsequence I use the O(n log n) method with an array tails, where tails[k] is the smallest possible end of an increasing subsequence of length k + 1. tails is itself sorted, so for each number I binary search the first entry at least as large and replace it, or append when there is none. A smaller end is easier to extend, so replacing never hurts, and the final length of tails is the answer. For non-decreasing subsequences I use upper bound instead of lower bound.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. The O(n log n) longest increasing subsequence method keeps an array tails. What is tails[k]?
  2. What is the length of the longest strictly increasing subsequence of [8, 3, 6, 1, 7, 4, 9, 2]?
  3. What is the time complexity of this code (n = len(a), tightest bound)?
    from bisect import bisect_left
    
    def lis(a):
        tails = []
        for x in a:
            i = bisect_left(tails, x)
            if i == len(tails):
                tails.append(x)
            else:
                tails[i] = x
        return len(tails)

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 11 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 5

#ProblemApproachRating
300Longest Increasing SubsequenceBuild the quadratic DP first, then explain why minimum tail values with binary search recover the optimal length.
646Maximum Length of Pair ChainCompare longest-chain DP with greedy selection by finishing time and explain the strict nonoverlap condition.
368Largest Divisible SubsetReplace size ordering with divisibility and reconstruct the actual subset through predecessor pointers.
1048Longest String ChainOrder words by length to form acyclic dependencies and find predecessors by deleting one character.Rating 1599
1218Longest Arithmetic Subsequence of Given DifferenceMap each value to its best length instead of enumerating predecessors, handling negative differences and duplicate values.Rating 1597

Advanced 6

#ProblemApproachRating
673Number of Longest Increasing SubsequenceMaintain both optimal length and number of ways, replacing inferior states and adding counts for equal-length states.
354Russian Doll EnvelopesSort equal widths in descending height to exclude invalid chains and reduce a strict two-dimensional order to one-dimensional LIS.
1027Longest Arithmetic SubsequenceWhen the difference is unknown, include it in the state to extend a one-dimensional state into a two-dimensional map.Rating 1759
873Length of Longest Fibonacci SubsequenceUse the previous two terms to determine the next, explaining why a pair of indices is needed instead of one ending value.Rating 1911
1626Best Team With No ConflictsResolve age-score conflicts through sorting and construct a maximum-weight nondecreasing subsequence.Rating 2027
1671Minimum Number of Removals to Make Mountain ArrayCombine LIS lengths from both directions and require nonempty sides of the peak to exclude monotonic sequences.Rating 1913