0
0
DSA Pythonprogramming

Why Intervals Are a Common Problem Pattern in DSA Python - Why This Pattern

Choose your learning style9 modes available
Mental Model
Intervals represent ranges of values that often overlap or need merging, making them a common pattern in problems involving scheduling or grouping.
Analogy: Imagine booking meeting rooms where each meeting has a start and end time; managing these bookings is like handling intervals to avoid clashes.
Intervals on a line:
[1---5]    [6---8]    [4---7]
Start and end points show where each interval begins and ends.
Dry Run Walkthrough
Input: Intervals: [1,5], [6,8], [4,7]
Goal: Understand how overlapping intervals cause complexity and why merging them is useful
Step 1: Look at first interval [1,5]
[1---5]    [6---8]    [4---7]
Why: Start with the first interval as a base for comparison
Step 2: Check second interval [6,8] against first
[1---5]    [6---8]    [4---7]
Why: No overlap since 6 > 5, intervals are separate
Step 3: Check third interval [4,7] against first and second
[1---5]    [6---8]    [4---7]
Why: Third interval overlaps with first (4 < 5) and second (7 > 6), causing complexity
Step 4: Merge overlapping intervals [1,5] and [4,7] into [1,7]
[1-------7]    [6---8]
Why: Merging reduces overlap and simplifies the problem
Step 5: Check merged interval [1,7] against [6,8]
[1-------7]    [6---8]
Why: These intervals overlap (7 >= 6), so they can be merged
Step 6: Merge [1,7] and [6,8] into [1,8]
[1-----------8]
Why: Final merged interval covers all overlapping ranges
Result:
[1-----------8] -- all overlapping intervals merged into one
Annotated Code
DSA Python
from typing import List

class Interval:
    def __init__(self, start: int, end: int):
        self.start = start
        self.end = end
    def __repr__(self):
        return f'[{self.start},{self.end}]'

def merge_intervals(intervals: List[Interval]) -> List[Interval]:
    if not intervals:
        return []
    # Sort intervals by start time
    intervals.sort(key=lambda x: x.start)
    merged = [intervals[0]]
    for current in intervals[1:]:
        last = merged[-1]
        if current.start <= last.end:
            # Overlapping intervals, merge them
            last.end = max(last.end, current.end)
        else:
            # No overlap, add current interval
            merged.append(current)
    return merged

# Driver code using dry_run input
intervals = [Interval(1,5), Interval(6,8), Interval(4,7)]
merged = merge_intervals(intervals)
print('Merged intervals:', ' '.join(map(str, merged)))
intervals.sort(key=lambda x: x.start)
Sort intervals by their start time to process in order
merged = [intervals[0]]
Initialize merged list with first interval as base
for current in intervals[1:]:
Iterate over remaining intervals to check overlap
if current.start <= last.end:
Check if current interval overlaps with last merged interval
last.end = max(last.end, current.end)
Merge intervals by extending the end if overlapping
merged.append(current)
Add non-overlapping interval to merged list
OutputSuccess
Merged intervals: [1,8]
Complexity Analysis
Time: O(n log n) because sorting the intervals takes O(n log n) and merging takes O(n)
Space: O(n) because in worst case no intervals overlap and all are stored in merged list
vs Alternative: Naive approach checks every pair for overlap leading to O(n^2), merging after sorting is more efficient
Edge Cases
Empty list of intervals
Returns empty list without error
DSA Python
if not intervals:
        return []
Intervals with no overlap
All intervals remain separate in merged list
DSA Python
else:
            merged.append(current)
Intervals fully contained within others
Smaller intervals merged into larger ones correctly
DSA Python
last.end = max(last.end, current.end)
When to Use This Pattern
When you see problems involving ranges, times, or segments that may overlap, think of intervals because merging or comparing them simplifies the problem.
Common Mistakes
Mistake: Not sorting intervals before merging
Fix: Always sort intervals by start time first to ensure correct merging order
Summary
Intervals represent ranges that often overlap and need merging.
Use interval patterns when handling scheduling, grouping, or range overlap problems.
Sorting intervals by start time and merging overlapping ones simplifies complex overlap scenarios.