0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

57. Insert Interval

Posted at

Input: 
    intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]]
    newInterval = [4,8]
    
Output: 
    [[1,2],[3,10],[12,16]]

Explanation: 
    Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]

CODE

def insert(intervals, newInterval):
    left, right = [], []
    newStart = newInterval[0]
    newEnd = newInterval[1]
    for i in intervals:
        if i[1] < newStart:
            left.append(i)
        elif i[0] > newEnd:
            right.append(i)
        else:
            newStart = min(i[0], newStart)
            newEnd = max(i[1], newEnd)
    middle = [[newStart, newEnd]]
    return left + middle + right

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?