MediumNo. 0646

Maximum Length of Pair Chain — LeetCode 646 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Dynamic Programming, Sorting
Reading time
2 min

The 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.

Example

Input
pairs = [[1,2],[2,3],[3,4]]
Output
2
Explanation
The longest chain is [1,2] -> [3,4].

Python solution

PythonSolution
class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        pairs.sort(key=lambda x: x[1])
        ans, pre = 0, -inf
        for a, b in pairs:
            if pre < a:
                ans += 1
                pre = b
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(log n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 646. Maximum Length of Pair Chain is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0435Non-overlapping IntervalsMedium
1262Greatest Sum Divisible by ThreeMedium
1363Largest Multiple of ThreeHard
1402Reducing DishesHard
2708Maximum Strength of a GroupMedium
0045Jump Game IIMedium

Frequently asked questions

How hard is LeetCode 646. Maximum Length of Pair Chain?

LeetCode 646. Maximum Length of Pair Chain is rated Medium on LeetCode.

What is the time complexity of LeetCode 646. Maximum Length of Pair Chain?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 646. Maximum Length of Pair Chain?

The Python solution on this page uses O(log n) auxiliary space.

What topics does LeetCode 646. Maximum Length of Pair Chain cover?

LeetCode 646. Maximum Length of Pair Chain is tagged Greedy, Array, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.