Insert Interval

Problem Summary

What is Being Asked?

Key Observations

Approach Taken

Why This Works

Main Concepts Used

Time & Space Complexity

Code

class Solution:
    def insert(
        self, intervals: List[List[int]], newInterval: List[int]
    ) -> List[List[int]]:
        if not intervals:
            return [newInterval]

        newStart, newEnd = newInterval
        isInserted = False
        for i, (curStart, curEnd) in enumerate(intervals):
            if newStart <= curStart:
                intervals.insert(i, newInterval)
                isInserted = True
                break
        if not isInserted: # insert at the end
            intervals.append(newInterval)

        result = []
        prev = None
        for curStart, curEnd in intervals:
            if not prev:
                prev = [curStart, curEnd]
                continue

            prevStart, prevEnd = prev
            if curStart <= prevEnd:
                prev = [prevStart, max(prevEnd, curEnd)]
            else:
                result.append(prev)
                prev = [curStart, curEnd]
        if prev:
            result.append(prev)

        return result

Common Mistakes / Things I Got Stuck On