 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Program to find one minimum possible interval to insert into an interval list in Python
Suppose we have a 2D list of numbers called intervals where each row represents [start, end] (inclusive) interval. For an interval [a, b] (a < b), its size is (b - a). We must add one interval to the given list such that, after merging all the intervals, we get exactly one range left. We have to find the minimum possible size of the added interval.
So, if the input is like intervals = [[15, 20],[30, 50]], then the output will be 10, as we can add the interval [20, 30] which is the smallest possible interval.
To solve this, we will follow these steps −
- events := a new list
- for each start and end time s, e in intervals, do- insert (s, 1) at the end of events
- insert (e, -1) at the end of events
 
- sort the list events
- curr_status := 0, last := null
- interval := a pair [0, 0]
- for each pair (time, status) in events, do- if curr_status is same as 0 and last and time > last, then- if interval[0] is same as 0, then- interval[0] := last
 
- interval[1] := time
 
- if interval[0] is same as 0, then
- last := time
- curr_status := curr_status + status
 
- if curr_status is same as 0 and last and time > last, then
- return interval[1] - interval[0]
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, intervals): events = [] for s, e in intervals: events.append((s, 1)) events.append((e, -1)) events.sort() curr_status = 0 last = None interval = [0, 0] for time, status in events: if curr_status == 0 and last and time > last: if interval[0] == 0: interval[0] = last interval[1] = time last = time curr_status += status return interval[1] - interval[0] ob = Solution() intervals = [[15, 20],[30, 50]] print(ob.solve(intervals))
Input
[[15, 20],[30, 50]]
Output
10
Advertisements
 