
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Intervals That Do Not Intersect the Cut Interval in Python
Suppose we have a sorted and disjoint intervals list and another list cut, that represents an interval. We have to delete all parts of intervals that are intersecting with cut interval, and return the new list.
So, if the input is like intervals = [[2, 11],[13, 31],[41, 61]] cut = [8, 46], then the output will be [[2, 8], [46, 61]]
To solve this, we will follow these steps −
- cut_start, cut_end := cut
- ans := a new list
- for each start, end in intervals, do
- if maximum of cut_start and start < minimum of end and cut_end, then
- if start < cut_start, then
- insert interval [start, cut_start] into ans
- if end > cut_end, then
- insert interval [cut_end, end] into ans
- if start < cut_start, then
- otherwise,
- if maximum of cut_start and start < minimum of end and cut_end, then
- return ans
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, intervals, cut): cut_start, cut_end = cut ans = [] for start, end in intervals: if max(cut_start, start) < min(end, cut_end): if start < cut_start: ans.append([start, cut_start]) if end > cut_end: ans.append([cut_end, end]) else: ans.append([start, end]) return ans ob = Solution() intervals = [[2, 11],[13, 31],[41, 61]] cut = [8, 46] print(ob.solve(intervals, cut))
Input
[[2, 11],[13, 31],[41, 61]], [8, 46]
Output
[[2, 8], [46, 61]]
Advertisements