DEV Community

Bernice Waweru
Bernice Waweru

Posted on

1 1

Merge Intervals

Instructions

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Approach

  1. Sort the input by starttime to have an ascending list for comparison.

  2. Iterate through sorted intervals and if start of a given interval is less than or equal to the most recent end time stored in the result list then,update the previous end time(ie most recent end time in the result list) based on the max of current prevEnd and end of current interval.

  3. If condition is not met append interval to result.

Implementation

def merge(self, intervals: List[List[int]]) -> List[List[int]]:

        intervals.sort()

        result = [intervals[0]]

        for start,end in intervals[1:]:

            prevEnd = result[-1][1]

            if start <= prevEnd:
                result[-1][1] =  max(prevEnd,end)
            else:
                result.append([start,end])
        return result
Enter fullscreen mode Exit fullscreen mode

Happy coding !!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay