Problem Description
Given an array of pairs where each pair is represented as [left, right] with left < right, determine the length of the longest chain that can be formed. A chain can be built by connecting pairs such that for two consecutive pairs [a, b] and [c, d], b < c. You may select the pairs in any order, and not all pairs must be used.
Key Insights
- Sort the pairs based on their second (right) element to make a greedy selection.
- The greedy approach ensures that by choosing the pair with the smallest end, you leave maximum space for subsequent pairs.
- After sorting, iterate through the list and select a pair if its start is greater than the end value of the last selected pair.
- This strategy results in the optimal solution.
Space and Time Complexity
Time Complexity: O(n log n) due to the sorting step.
Space Complexity: O(1) if we ignore the space used to store the input.
Solution
The solution involves sorting the pairs by their right endpoints. Start with a variable to keep track of the current end of the chain (initialized to negative infinity) and a counter for the chain length. Iterate over the sorted pairs; if the current pair's start is greater than the current end, it can be added to the chain. Update the counter and the current end accordingly. This greedy method ensures the longest possible chain is built by always choosing the next available pair that leaves room for as many subsequent pairs as possible.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java.