How to make this Python Solution more Efficient?


  • 0
    M

    I know this solution is super convoluted so looking for advice to trim it down:

    class Solution(object):
        def merge(self, intervals):
            """
            :type intervals: List[Interval]
            :rtype: List[Interval]
            """
            n = len(intervals)
            if n <= 1: return intervals
            intervals.sort(key=lambda i: i.start)
            ret = []
            i, j = 0, 1
            while j < len(intervals):
                first, second = intervals[i], intervals[j]
                new_interval = None
                while first.end >= second.start:
                    new_interval = Interval(first.start, max(first.end, second.end))
                    intervals.insert(j+1, new_interval)
                    i = j + 1
                    j = i + 1
                    if j >= len(intervals):
                        break
                    first, second = intervals[i], intervals[j]
                if new_interval:
                    ret.append(new_interval)
                else:
                    ret.append(first)
                i = j
                j = i + 1
            
            if j == len(intervals):
                first, second = intervals[-2], intervals[-1] 
                if first.end >= second.start:
                    new_interval = Interval(first.start, second.end)
                    ret.append(new_interval)
                else:
                    ret.append(second)
            
            return ret
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.