- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

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

Suppose we have a list of boxes, here 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 blocks = [ [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]

To solve this, we will follow these steps:

if boxes are empty, then

return 0

sort the list boxes

dic := an empty map

for each start s and end e in boxes, do

dic[e] := maximum of dic[e] and dic[s] + 1

return maximum of the list of all values of dic

Let us see the following implementation to get better understanding:

## Example

import collections class Solution: def solve(self, boxes): if not boxes: return 0 boxes.sort() dic = collections.defaultdict(int) for s, e in boxes: dic[e] = max(dic[e], dic[s] + 1) return max(dic.values()) ob = Solution() boxes = [ [4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ] print(ob.solve(boxes))

## Input

[[4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ]

## Output

4

- Related Articles
- Program to find length of longest diminishing word chain in Python?
- Program to find longest distance of 1s in binary form of a number using Python
- Program to find maximum number of boxes we can fit inside another boxes in python
- Program to find number of rectangles that can form the largest square in Python
- Program to find longest consecutive run of 1s in binary form of n in Python
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Program to find out the number of boxes to be put into the godown in Python
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find longest awesome substring in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python

Advertisements