Welcome to Day 5 of your coding interview journey.
So far, youβve learned:
- β Day 1: HashMaps
- β Day 2: Sliding Window
- β Day 3: Arrays
- β Day 4: Two Pointers
Todayβs focus is a very common interview pattern:
π Interval Problems
These questions test your ability to handle ranges, overlaps, and sorting logic.
π§ What Are Interval Problems?
You are given a list of intervals:
[start, end]
And asked to:
- Merge them
- Find overlaps
- Insert new intervals
- Determine conflicts
π When Should You Use This Pattern?
Look for:
- Ranges of time (meetings, schedules)
- Overlapping segments
- Start and end values
- Questions involving merging or conflicts
π‘ Problem β Merge Intervals
π§© Problem
Given an array of intervals where intervals[i] = [start, end]:
π Merge all overlapping intervals and return the result.
β Example
intervals = [[1,3],[2,6],[8,10],[15,18]]
Output:
[[1,6],[8,10],[15,18]]
β Brute Force Idea
- Compare every interval with every other
π Time Complexity: O(nΒ²)
Too slow for interviews.
β Optimal Approach β Sort + Merge
π§ Key Idea
- Sort intervals by start time
- Compare current interval with the last merged one
- Merge if overlapping, otherwise add new interval
π οΈ Solution in Python
def merge_intervals(intervals):
# Step 1: Sort by start time
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
# Check overlap
if current[0] <= last[1]:
# Merge intervals
last[1] = max(last[1], current[1])
else:
merged.append(current)
return merged
π― Step-by-Step Intuition
Input:
[1,3], [2,6]
- Since
2 <= 3β overlap - Merge β
[1,6]
β‘ Complexity Analysis
- Time:
O(n log n)(sorting) - Space:
O(n)(result)
π₯ Key Pattern
π Sort first, then process linearly
This pattern appears in MANY problems.
β οΈ Common Mistakes
- β Forgetting to sort intervals
- β Incorrect overlap condition
- β Not updating the merged interval correctly
- β Edge cases (single interval, empty input)
π§ͺ Practice Problems
To master intervals, try:
- Insert Interval
- Non-overlapping intervals
- Meeting rooms I & II
- Minimum number of arrows to burst balloons
- Employee free time
π― Key Takeaways
- Interval problems almost always start with sorting
- Focus on:
- Overlap detection
- Merging logic
- Reduce complexity by avoiding nested loops
π Your Challenge (Day 5)
Solve this:
Given a list of meeting intervals, determine if a person can attend all meetings.
(Hint: check for overlaps after sorting π)
π Final Thoughts
Interval problems are extremely common in real-world scenarios:
- Scheduling systems
- Calendar apps
- Resource allocation
Mastering them gives you a huge advantage in interviews.