Maximum Length of Pair Chain (LeetCode 646): Solution and Explanation
Each pair is an interval [left, right]. A pair can follow another only if it starts strictly after the other ends. Pick pairs in any order and find the longest chain.
Intuition
Draw every pair as a segment on a number line. A chain is a set of segments that do not touch, read from left to right. So the question is really how many disjoint segments you can pick, which is the classic interval scheduling problem.
Suppose you are building the chain from the left. Of all the pairs that could go next, take the one that ends first. Any chain that used a different pair there could swap in yours, since yours ends no later, and everything after it would still fit.
That suggests sorting by right end and walking once: keep the right end of the last pair you took, and take each new pair whose left end is beyond it.
Approach: Greedy by earliest right end
- Sort
pairsby their right end. - Set
cur = -inf(the end of the empty chain) andcount = 0. - For each pair
[left, right]in sorted order, ifleft > cur, take it:cur = rightandcount += 1. - Otherwise it overlaps the last chosen pair; skip it.
- Return
count.
Step-by-step example
pairs = [[1,2],[2,3],[3,4]]
- Sorted by right end the order stays [1,2], [2,3], [3,4]. cur = -inf, count = 0.
- [1,2]: 1 > -inf, so take it. cur = 2, count = 1.
- [2,3]: 2 is not greater than 2, so it touches [1,2]. Skip it.
- [3,4]: 3 > 2, so take it. cur = 4, count = 2.
- The answer is 2: [1,2] -> [3,4].
Code: Python, Java, C++
1class Solution:
2 def findLongestChain(self, pairs: List[List[int]]) -> int:
3 pairs.sort(key=lambda p: p[1])
4 cur = float('-inf')
5 count = 0
6 for left, right in pairs:
7 if left > cur:
8 cur = right
9 count += 1
10 return count1class Solution {
2 public int findLongestChain(int[][] pairs) {
3 Arrays.sort(pairs, (a, b) -> Integer.compare(a[1], b[1]));
4 int cur = Integer.MIN_VALUE;
5 int count = 0;
6 for (int[] p : pairs) {
7 if (p[0] > cur) {
8 cur = p[1];
9 count++;
10 }
11 }
12 return count;
13 }
14}1class Solution {
2public:
3 int findLongestChain(vector<vector<int>>& pairs) {
4 sort(pairs.begin(), pairs.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
5 int cur = INT_MIN;
6 int count = 0;
7 for (const auto& p : pairs) {
8 if (p[0] > cur) {
9 cur = p[1];
10 count++;
11 }
12 }
13 return count;
14 }
15};Time and space complexity
O(n log n)
Sorting dominates. The walk over the sorted pairs is a single O(n) pass.
O(1)
Only cur and count are kept beyond the sort, which works in place (the sort itself may use O(log n) stack).
Other approaches
DP like Longest Increasing Subsequence (time O(n^2), space O(n))
Sort by left end and let dp[i] be the longest chain ending with pair i. For each j < i with pairs[j][1] < pairs[i][0], dp[i] = max(dp[i], dp[j] + 1). Correct, but quadratic.
Sort by left end, keep the smallest end (time O(n log n), space O(1))
Sort by left end. When a pair overlaps the current last pair, replace the last pair if the new one ends sooner. This is the same greedy idea seen from the other side.
Common mistakes
- Using >= instead of >. The condition is strict: [1,2] and [2,3] cannot be chained because 2 is not less than 2.
- Sorting by left end and taking pairs greedily. A long pair that starts early, like [1,10], would block [2,3], [4,5] and [6,7].
- Starting cur at 0 or at the first pair's left end. Values can be negative down to -1000, so begin at minus infinity (or take the first sorted pair unconditionally).
- Assuming the input order must be kept. The problem lets you choose pairs in any order, which is what makes sorting allowed.
Frequently asked questions
Why is sorting by right end correct?
The first pair you pick should end as early as possible. Swapping it into any optimal chain keeps the chain valid, because everything after it started after a later end anyway. Repeating the argument for each pick proves the greedy chain is as long as any other.
How is this related to Non-overlapping Intervals?
It is the complement. Non-overlapping Intervals asks how many intervals to remove so the rest do not overlap; that equals n minus the longest chain, with the small difference that touching endpoints are allowed there but not here.
Why is this filed under dynamic programming?
The O(n^2) LIS-style DP is a natural first solution, and LeetCode tags it that way. The greedy is the faster version of the same idea.