#646

Maximum Length of Pair Chain

Medium
ArrayDynamic ProgrammingGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the pairs based on their end values and using a greedy approach, we can efficiently find the longest chain without checking all combinations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the pairs based on the second element (right value).
  2. 2Step 2: Initialize a variable to track the end of the last added pair in the chain.
  3. 3Step 3: Iterate through the sorted pairs, and for each pair, check if it can be added to the chain (i.e., if its left value is greater than the last end). If yes, update the end and increase the count.
solution.py11 lines
1# Full working Python code
2
3def findLongestChain(pairs):
4    pairs.sort(key=lambda x: x[1])
5    count = 0
6    last_end = float('-inf')
7    for left, right in pairs:
8        if last_end < left:
9            count += 1
10            last_end = right
11    return count

Complexity note: The time complexity is O(n log n) due to the sorting step, which is much more efficient than the brute-force approach.

  • 1Sorting the pairs by their end values allows us to efficiently build the longest chain.
  • 2Using a greedy approach helps in making optimal choices at each step without backtracking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.