Maximum Length of Pair Chain - Problem

You're given an array of n pairs where each pair is represented as pairs[i] = [left_i, right_i] with left_i < right_i.

A pair p2 = [c, d] can follow a pair p1 = [a, b] if b < c (the right value of the first pair is strictly less than the left value of the second pair).

Your goal is to form the longest possible chain of pairs following this rule. You can select pairs in any order and don't need to use all pairs.

Example:
Input: [[1,2], [2,3], [3,4]]
Output: 2 (chain: [1,2] โ†’ [3,4])
Note: [2,3] cannot follow [1,2] since 2 is not less than 2

Input & Output

example_1.py โ€” Basic Chain
$ Input: pairs = [[1,2], [2,3], [3,4]]
โ€บ Output: 2
๐Ÿ’ก Note: The longest chain is [1,2] โ†’ [3,4]. Note that [2,3] cannot follow [1,2] because 2 is not strictly less than 2.
example_2.py โ€” Multiple Valid Chains
$ Input: pairs = [[1,2], [7,8], [4,5]]
โ€บ Output: 3
๐Ÿ’ก Note: All pairs can be chained together: [1,2] โ†’ [4,5] โ†’ [7,8], giving us a chain of length 3.
example_3.py โ€” Single Pair
$ Input: pairs = [[1,3]]
โ€บ Output: 1
๐Ÿ’ก Note: With only one pair, the maximum chain length is 1.

Visualization

Tap to expand
Meeting Room SchedulerTime โ†’[1,2] Meeting AEnds: 2[2,3] Meeting BEnds: 3[3,4] Meeting CEnds: 4โœ“โœ—โœ“Selected: Meeting A ends at 2Rejected: Meeting B starts at 2 (not > 2)Selected: Meeting C starts at 3 (3 > 2)Valid chain๐ŸŽฏ Key Insight:Sorting by end time ensures we always leave maximum roomfor future meetings. This greedy choice is always optimal!Result: 2 meetings scheduled ([1,2] โ†’ [3,4])
Understanding the Visualization
1
Sort by End Time
Arrange all meetings by when they end - this is key to the greedy strategy
2
Pick Earliest Ending
Always select the meeting that ends earliest among available options
3
Check Compatibility
Only book meetings that start after the previous one completely ends
4
Maximize Bookings
This greedy choice leads to the maximum number of scheduled meetings
Key Takeaway
๐ŸŽฏ Key Insight: Sorting by end time and using a greedy approach guarantees the maximum chain length because it always preserves the most opportunities for future selections.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^n * n!)

2^n subsets, each potentially requiring n! permutations to check

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Space for recursion stack and storing current chain

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 1000 where n is the length of pairs
  • -1000 โ‰ค lefti < righti โ‰ค 1000
  • lefti < righti for all pairs
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
68.2K Views
Medium Frequency
~15 min Avg. Time
1.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