The Merge Intervals pattern is commonly used in coding interviews to solve problems involving overlapping or merging intervals. It's particularly useful when dealing with problems related to scheduling, time intervals, or event management. Let me explain the pattern and provide you with an example question and its solution.
Pattern: Merge Intervals
Now, let's see an example question and its solution using the Merge Intervals pattern.
Example Question: Given a list of intervals representing the start and end time of meetings, find all the intervals when a person is busy, considering that the person can attend only one meeting at a time.
Example: Intervals: [(1, 4), (2, 5), (7, 9)] Output: [(1, 5), (7, 9)] Explanation: The person is busy from 1 to 5 (attending meetings 1 and 2) and from 7 to 9 (attending meeting 3).
Solution:
def merge_intervals(intervals): if len(intervals) < 2: return intervals intervals.sort(key=lambda x: x[0]) # Sort intervals based on start time merged = [] start, end = intervals[0] for i in range(1, len(intervals)): interval = intervals[i] if interval[0] <= end: # Overlapping intervals end = max(end, interval[1]) else: # Non-overlapping interval found merged.append((start, end)) start, end = interval merged.append((start, end)) # Add the last interval return merged # Testing the function intervals = [(1, 4), (2, 5), (7, 9)] print(merge_intervals(intervals))
Output: [(1, 5), (7, 9)]
The solution follows the Merge Intervals pattern by first sorting the intervals based on their start time. Then, it iterates through the sorted intervals, merging the overlapping intervals and adding the non-overlapping intervals to the result list. Finally, it adds the last interval to the result list. In the provided example, the output correctly identifies the busy intervals when the person is attending meetings.