Program to find number of boxes that form longest chain in Python?

Suppose we have a list of boxes, where each entry has two values [start, end] (start < end). We can join two boxes if the end of one is equal to the start of another. We have to find the length of the longest chain of boxes.

So, if the input is like boxes = [[4, 5], [5, 6], [4, 8], [1, 2], [2, 4]], then the output will be 4, as we can form the chain: [1, 2] ? [2, 4] ? [4, 5] ? [5, 6]

Algorithm

To solve this, we will follow these steps ?

  • If boxes list is empty, return 0

  • Sort the list of boxes to process them in order

  • Create a dictionary to store the maximum chain length ending at each value

  • For each box [start, end], update the maximum chain length ending at 'end'

  • Return the maximum chain length from all ending points

Example

Let us see the following implementation to get better understanding ?

import collections

class Solution:
    def solve(self, boxes):
        if not boxes:
            return 0
        
        boxes.sort()
        dic = collections.defaultdict(int)
        
        for start, end in boxes:
            dic[end] = max(dic[end], dic[start] + 1)
        
        return max(dic.values())

# Test the solution
ob = Solution()
boxes = [
    [4, 5],
    [5, 6],
    [4, 8],
    [1, 2],
    [2, 4]
]
print("Longest chain length:", ob.solve(boxes))
Longest chain length: 4

How It Works

The algorithm uses dynamic programming with a dictionary approach ?

  • After sorting, boxes are processed in order: [[1, 2], [2, 4], [4, 5], [4, 8], [5, 6]]

  • For each box [start, end], we check if we can extend a chain ending at 'start'

  • The dictionary stores the maximum chain length that ends at each value

  • Final result is the maximum value from all possible ending points

Alternative Implementation

Here's a more detailed version with step-by-step tracking ?

def find_longest_chain(boxes):
    if not boxes:
        return 0
    
    # Sort boxes by start value
    boxes.sort()
    print("Sorted boxes:", boxes)
    
    # Dictionary to store max chain length ending at each value
    chain_lengths = {}
    
    for start, end in boxes:
        # Maximum chain length ending at 'end' is either:
        # 1. Current chain length at 'end' 
        # 2. Chain length at 'start' + 1 (extending existing chain)
        current_length = chain_lengths.get(end, 0)
        extended_length = chain_lengths.get(start, 0) + 1
        chain_lengths[end] = max(current_length, extended_length)
        
        print(f"Box [{start}, {end}] ? Chain lengths: {chain_lengths}")
    
    return max(chain_lengths.values())

# Test the function
boxes = [[4, 5], [5, 6], [4, 8], [1, 2], [2, 4]]
result = find_longest_chain(boxes)
print(f"\nLongest chain length: {result}")
Sorted boxes: [[1, 2], [2, 4], [4, 5], [4, 8], [5, 6]]
Box [1, 2] ? Chain lengths: {2: 1}
Box [2, 4] ? Chain lengths: {2: 1, 4: 2}
Box [4, 5] ? Chain lengths: {2: 1, 4: 2, 5: 3}
Box [4, 8] ? Chain lengths: {2: 1, 4: 2, 5: 3, 8: 3}
Box [5, 6] ? Chain lengths: {2: 1, 4: 2, 5: 3, 8: 3, 6: 4}

Longest chain length: 4

Conclusion

This dynamic programming solution efficiently finds the longest chain by sorting the boxes and tracking maximum chain lengths at each endpoint. The time complexity is O(n log n) due to sorting, and space complexity is O(n) for the dictionary storage.

Updated on: 2026-03-25T12:10:05+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements