Maximum Length of Pair Chain - Problem

You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

Return the length of the longest chain which can be formed. You do not need to use up all the given intervals. You can select pairs in any order.

Input & Output

Example 1 — Basic Chain
$ Input: pairs = [[1,2],[2,3],[3,4]]
Output: 2
💡 Note: The longest chain is [1,2] → [3,4]. We can't use [2,3] because 2 is not less than 2.
Example 2 — All Can Chain
$ Input: pairs = [[1,2],[7,8],[4,5]]
Output: 3
💡 Note: After sorting by end time: [1,2] → [4,5] → [7,8]. All pairs can form a valid chain.
Example 3 — No Chaining Possible
$ Input: pairs = [[1,4],[2,3]]
Output: 1
💡 Note: Cannot chain [1,4] → [2,3] because 4 ≥ 2. Maximum chain length is 1.

Constraints

  • n == pairs.length
  • 1 ≤ n ≤ 1000
  • -1000 ≤ lefti < righti ≤ 1000

Visualization

Tap to expand
Maximum Length of Pair Chain INPUT Array of Pairs: [1, 2] [2, 3] [3, 4] Visual on Number Line: 1 2 3 4 [1,2] [2,3] [3,4] pairs = [[1,2],[2,3],[3,4]] n = 3 pairs Chain: p2 follows p1 if b < c ALGORITHM STEPS Greedy - Activity Selection 1 Sort by End Time Sort pairs by right_i value [1,2] [2,3] [3,4] (already sorted) 2 Select First Pair Pick [1,2], chain=1, end=2 3 Check Next Pairs If left_i > current end, add [2,3]: 2 > 2? NO (skip) [3,4]: 3 > 2? YES (add) chain=2, end=4 4 Return Result No more pairs, return 2 FINAL RESULT Longest Chain Found: [1, 2] [3, 4] 2 follows 2? 3 > 2 = YES Skipped Pair: [2, 3] (overlaps with [1,2]) OUTPUT 2 Maximum chain length Key Insight: This is the classic Activity Selection problem. By sorting pairs by their end times and greedily selecting non-overlapping pairs (where next start > current end), we maximize the chain length. Time: O(n log n) for sorting. Greedy choice: always pick the pair that ends earliest to leave room for more. TutorialsPoint - Maximum Length of Pair Chain | Greedy - Activity Selection
Asked in
Google 15 Amazon 12 Facebook 8
98.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen