Back to blog
Dec 12, 2024
3 min read

LeetCode 646: Maximum Length of Pair Chain

Leetcode 646: Maximum Length of Pair Chain solution in Python

Problem Description

LeetCode Problem 646

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 longest chain which can be formed.

You do not need to use up all the given intervals. You can select pairs in any order.

 

Example 1:

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

Example 2:

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

 

Constraints:

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

Difficulty: Medium

Tags: array, dynamic programming, greedy, sorting

Rating: 97.23%

Solution

Here’s my Python solution to this problem:

class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        pairs.sort(key=lambda x:x[1])
        print(pairs)

        cur_end = -float('inf')
        res = 0

        for l, r in pairs:
            if l > cur_end:
                cur_end = r
                res += 1
        
        return res

Example Walkthrough

Let’s walk through an example to understand the solution better.

pairs = [[1,2],[7,8],[4,5]]
  1. Sort the pairs based on the second element of each pair:
pairs = [[1,2],[4,5],[7,8]]
  1. Initialize the current end of the chain and the result:
cur_end = -inf
res = 0
  1. Iterate through the pairs:
  • For the first pair [1,2], the left element is greater than the current end. So, we update the current end to 2 and increment the result by 1.
cur_end = 2
res = 1
  • For the second pair [4,5], the left element is greater than the current end. So, we update the current end to 5 and increment the result by 1.
cur_end = 5
res = 2
  • For the third pair [7,8], the left element is greater than the current end. So, we update the current end to 8 and increment the result by 1.
cur_end = 8
res = 3
  1. Return the result 3.
return 3

Complexity Analysis

The solution has the following complexity characteristics:

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1)

Note: This is an automated analysis and may not capture all edge cases or specific algorithmic optimizations.