- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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:

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))

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

4

- Related Questions & Answers
- 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 1 in binary form of a number in C++
- Length of longest string chain in JavaScript
- Longest String Chain 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 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