- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to merge intervals and sort them in ascending order in Python
Suppose we have a list intervals, we have to find the union of them in sorted sequence.
So, if the input is like inv = [[2, 5],[4, 10],[20, 25]], then the output will be [[2, 10], [20, 25]]
To solve this, we will follow these steps −
- sort the list intervals
- ans := a new list
- for each start and end (s, e) in intervals, do
- if ans and s <= ending time of the last interval of ans, then
- ending time of the last interval of ans := maximum of e and ending time of the last interval of ans
- otherwise,
- insert interval [s, e] into ans
- if ans and s <= ending time of the last interval of ans, then
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, intervals): intervals.sort() ans = [] for s, e in intervals: if ans and s <= ans[-1][1]: ans[-1][1] = max(ans[-1][1], e) else: ans.append([s, e]) return ans ob = Solution() inv = [[2, 5],[4, 10],[20, 25]] print(ob.solve(inv))
Input
[[2, 5],[4, 10],[20, 25]]
Output
[[2, 10], [20, 25]]
Advertisements