Maximum Length of Pair Chain

Updated on 12 June, 2025
Maximum Length of Pair Chain header image

Problem Statement

In this task, we are provided with an array called pairs, consisting of n pairs where each pair, indicated by pairs[i] = [lefti, righti], holds a relationship where lefti is less than righti. The objective is to determine the length of the longest possible sequence or chain of pairs. A pair p2 = [c, d] can instantly follow a pair p1 = [a, b] only if the second element of p1 (b) is less than the first element of p2 (c). When forming these chains, it is not mandatory to use all the given pairs and the pairs can be reordered as necessary to form the longest chain.

Examples

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

Approach and Intuition

  • For each example given, it can be observed that a chain formation follows the rule of sequencing pairs based on the "earlier ends first" criteria for sorting pairs.

  • By sorting these pairs primarily by the second element (righti), it naturally lines up the pairs in a sequence where the end of one is less than the start of the next, allowing an easier formation of a chain.

  • Here are the steps to achieve this solution:

    1. Sort the list of pairs based on their second elements (righti).
    2. Start with the first pair in the sorted list and consider it as the starting point of your chain.
    3. Sequentially scan through the sorted list and select the next available pair that can follow the current pair. A pair can follow the current one if its start (left) is greater than the end (right) of the last pair in the existing chain.
    4. Each time a valid pair is found, it is added to the chain, and the counter for the longest chain length increases.
    5. Continue this process until all pairs are considered.
  • In Example 1:

    • The input pairs are [[1,2],[2,3],[3,4]].
    • Sorting by second elements does not change the order: [[1,2],[2,3],[3,4]].
    • Beginning from [1,2], the chain can extend to [3,4] (as 2 < 3), but cannot include [2,3] in the same sequence.
    • Thus, the longest chain length is 2: [1,2] -> [3,4].
  • In Example 2:

    • The input pairs are [[1,2], [7,8], [4,5]].
    • Sorting by second elements will reorder to [[1,2], [4,5], [7,8]].
    • Each pair can sequentially follow from the previous with the end of one being less than the start of the next, forming a continuous chain from start to end.
    • Thus, the longest chain length here is 3: [1,2] -> [4,5] -> [7,8].

By following the described approach, which utilizes sorting and a greedy method of extending the chain, we efficiently find the maximum length of a pair chain that follows the given "follows" condition.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int findMaxChain(vector<vector<int>>& pairs) {
        // Sorting pairs using the second element to determine order
        sort(pairs.begin(), pairs.end(),
             [](const vector<int>& x, const vector<int>& y) { return x[1] < y[1]; });
        int last_end = INT_MIN, max_chain = 0;

        for (const auto& pair : pairs) {
            if (pair[0] > last_end) {
                max_chain++;
                last_end = pair[1];
            }
        }
        return max_chain;
    }
};

The given program is written in C++ and solves the problem of finding the maximum length of a pair chain. The task is accomplished by defining a class Solution which includes a public method named findMaxChain.

  • The method receives a 2D vector pairs containing pairs of integers.

  • The solution approaches the problem by first sorting the pairs vector. The sorting criterion is based on the second element of each pair, ensuring that pairs are sorted by their end points in ascending order.

  • After sorting, the method iterates through each sorted pair, utilizing a greedy algorithm to construct the longest chain. The algorithm keeps track of the last end point of the chain in last_end and initializes it with the smallest possible integer value using INT_MIN.

  • During the iteration, for each pair, if the start point of the current pair is greater than last_end, it implies that this pair can be added to the chain. In this case, the chain length max_chain is incremented by one, and last_end is updated to the end point of the current pair to reflect the new end of the chain.

  • Finally, after processing all pairs, the maximum chain length max_chain is returned as the result.

This solution effectively uses a greedy algorithm, leveraging the sorted order of the pairs to ensure that each pair added to the chain is optimal, leading to the maximum possible length of the chain. The use of sorting followed by a single sweep through the data results in efficient computation.

java
class Solution {
    public int findMaxChainLength(int[][] intervals) {
        // Sorting intervals by the second element in ascending order
        Arrays.sort(intervals, (x, y) -> x[1] - y[1]);
        int endpoint = Integer.MIN_VALUE;
        int count = 0;

        for (int[] interval : intervals) {
            if (interval[0] > endpoint) {
                count++;
                endpoint = interval[1];
            }
        }
        return count;
    }
}

The provided Java solution is designed to address the problem of finding the maximum length of a chain of pairs, where each pair consists only of intervals that do not overlap. The function findMaxChainLength capitalizes on a greedy algorithm approach:

  1. The function sorts an array of interval pairs by the second element of each pair in ascending order. This ordering aids in determining the maximum chain length by focusing on intervals with earlier end times first, which potentially leaves room to include more intervals before hitting an overlap.

  2. It initializes two variables, endpoint set to the minimum integer value and count set to zero. endpoint will keep track of the current chain's end, and count will hold the total number of non-overlapping intervals in the chain.

  3. The function enters a loop over the sorted intervals:

    • If the starting point of the current interval is greater than the endpoint, it signifies that this interval does not overlap with the previous one. Consequently, the interval is added to the chain by incrementing count and updating endpoint to the current interval's endpoint.
  4. Finally, the function returns the count, which reflects the maximum number of non-overlapping intervals in the chain.

This efficient implementation leverages sorting and a greedy choice of smallest end times to maximize the chain's length, ensuring optimal performance by minimizing unnecessary checks or operations.

python
class Solution:
    def longestChain(self, pairList: List[List[int]]) -> int:
        pairList.sort(key=lambda pair: pair[1])
        last = float('-inf')
        count = 0

        for pair in pairList:
            if pair[0] > last:
                count += 1
                last = pair[1]
        return count

This Python solution addresses finding the maximum length of a pair chain given a list of pairs. Here's a breakdown of the approach taken in the code:

  • Start by sorting pairList based on the second element of each pair. This sorting is crucial as it allows for a greedy approach where you always consider the smallest available end value to lengthen the chain.

  • Initialize last with negative infinity and count with zero. last tracks the end point of the last pair added to the chain, and count keeps a tally of the number of pairs in the current longest chain.

  • Iterate through the sorted pairList. For each pair, check if the starting element is greater than last. If true, this means the current pair can be appended to the chain:

    • Increment count by one to acknowledge the addition of the new pair to the chain.
    • Update last to the end of the current pair, indicating the new endpoint of the chain.
  • Finally, return count, which represents the length of the longest possible chain of pairs where each pair's first element is greater than the previous pair's second element.

This solution efficiently compiles the longest sequence of compatible pairs using a sort-and-scan approach, suitable for problems where constraints optimize for minimal overlapping between intervals or segments.

Comments

No comments yet.