
- 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 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]]
- Related Articles
- Program to find overlapping intervals and return them in ascending order in Python
- Sort index in ascending order – Python Pandas
- Python program to sort out words of the sentence in ascending order
- Program to sort a given linked list into ascending order in python
- Python program to sort the elements of an array in ascending order
- 8085 Program to perform selection sort in ascending order
- 8085 Program to perform bubble sort in ascending order
- Golang Program To Sort An Array In Ascending Order Using Insertion Sort
- 8086 program to sort an integer array in ascending order
- Java program to sort words of sentence in ascending order
- C program to sort an array in an ascending order
- Java Program to Sort Array list in an Ascending Order
- Merge Intervals in Python
- Program to perform bubble sort in ascending order in 8085 Microprocessor
- Program to perform selection sort in ascending order in 8085 Microprocessor

Advertisements