Interval problems involve ranges like [start, end]. Key techniques: sort by start time, then merge overlapping intervals. Common patterns: merge intervals, insert interval, meeting rooms, interval intersection, and minimum intervals to remove.
✦ Definition~90s read
What is Interval and Range Interview Problems?
Interval and range problems involve manipulating ranges of numbers or time, often requiring sorting and merging overlapping intervals.
★
Think of intervals as time slots on a calendar.
Plain-English First
Think of intervals as time slots on a calendar. If two meetings overlap, you might need to merge them into one longer slot. Sorting by start time helps you process them in order, just like scanning your day chronologically.
Interval and range problems are a staple in coding interviews, especially at top tech companies. They test your ability to handle overlapping ranges, optimize scheduling, and manage edge cases. From merging calendar events to finding free time slots, these problems have real-world applications in scheduling, resource allocation, and data processing. In this guide, we'll cover the most common interval patterns, provide step-by-step solutions with time and space complexity, and share tips to ace your interview. Whether you're a beginner or looking to brush up, this tutorial will equip you with the tools to tackle any interval problem confidently.
The classic interval problem: given a collection of intervals, merge all overlapping intervals. The key is to sort by start time, then iterate. If the current interval overlaps with the last merged interval (i.e., current.start <= last.end), update the end to max(last.end, current.end). Otherwise, add the last merged interval to the result and start a new one. Finally, add the last interval after the loop. This runs in O(n log n) due to sorting, and O(n) space for the output.
merge_intervals.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
defmerge(intervals):
ifnot intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
last_end = merged[-1][1]
if start <= last_end:
merged[-1][1] = max(last_end, end)
else:
merged.append([start, end])
return merged
Output
[[1,6],[8,10],[15,18]] for input [[1,3],[2,6],[8,10],[15,18]]
💡Interview Tip
📊 Production Insight
In production, intervals might be large; consider in-place merging to save space.
🎯 Key Takeaway
Sorting by start time is the foundation for most interval problems.
2. Insert Interval
You are given a set of non-overlapping intervals sorted by start time, and a new interval to insert. Merge if necessary. Traverse the list and handle three cases: intervals that end before the new interval starts (add directly), intervals that start after the new interval ends (add new interval then the rest), and overlapping intervals (merge by updating start and end). This is O(n) time and O(n) space.
insert_interval.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
definsert(intervals, newInterval):
result = []
i = 0
n = len(intervals)
# add all intervals ending before newInterval startswhile i < n and intervals[i][1] < newInterval[0]:
result.append(intervals[i])
i += 1# merge overlapping intervalswhile i < n and intervals[i][0] <= newInterval[1]:
newInterval[0] = min(newInterval[0], intervals[i][0])
newInterval[1] = max(newInterval[1], intervals[i][1])
i += 1
result.append(newInterval)
# add remaining intervalswhile i < n:
result.append(intervals[i])
i += 1return result
Output
[[1,5],[6,9]] for intervals [[1,3],[6,9]] and newInterval [2,5]
🔥Edge Cases
🎯 Key Takeaway
Insert interval is a variation of merge intervals with a single new interval.
3. Meeting Rooms (Leetcode 252)
Determine if a person can attend all meetings. Given an array of meeting time intervals, return true if no two meetings overlap. Simply sort by start time and check if any meeting starts before the previous ends. O(n log n) time, O(1) space.
meeting_rooms.pyPYTHON
1
2
3
4
5
6
defcanAttendMeetings(intervals):
intervals.sort(key=lambda x: x[0])
for i inrange(1, len(intervals)):
if intervals[i][0] < intervals[i-1][1]:
returnFalsereturnTrue
Output
False for [[0,30],[5,10],[15,20]]
⚠ Common Mistake
🎯 Key Takeaway
Checking for overlap is as simple as comparing start with previous end.
4. Meeting Rooms II (Leetcode 253)
Find the minimum number of conference rooms required. Use a min-heap to track end times of ongoing meetings. Sort intervals by start time. For each meeting, if the room with the earliest end time is free (end <= start), reuse it; otherwise, allocate a new room. The heap size at the end is the answer. O(n log n) time, O(n) space.
meeting_rooms_ii.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
import heapq
defminMeetingRooms(intervals):
ifnot intervals:
return0
intervals.sort(key=lambda x: x[0])
heap = []
heapq.heappush(heap, intervals[0][1])
for start, end in intervals[1:]:
if heap[0] <= start:
heapq.heappop(heap)
heapq.heappush(heap, end)
returnlen(heap)
Output
2 for [[0,30],[5,10],[15,20]]
💡Alternative Approach
🎯 Key Takeaway
Min-heap efficiently tracks the earliest ending meeting to free up rooms.
5. Interval List Intersections (Leetcode 986)
Given two lists of closed intervals, each sorted by start time, return the intersection of these interval lists. Use two pointers. For each pair, the intersection is [max(start1, start2), min(end1, end2)] if start <= end. Then advance the pointer with the smaller end. O(m+n) time, O(k) space for output.
interval_intersection.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
defintervalIntersection(A, B):
i = j = 0
result = []
while i < len(A) and j < len(B):
start = max(A[i][0], B[j][0])
end = min(A[i][1], B[j][1])
if start <= end:
result.append([start, end])
if A[i][1] < B[j][1]:
i += 1else:
j += 1return result
Output
[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] for A=[[0,2],[5,10],[13,23],[24,25]], B=[[1,5],[8,12],[15,24],[25,26]]
🔥Key Insight
🎯 Key Takeaway
Two-pointer technique works well when both lists are sorted.
6. Non-overlapping Intervals (Leetcode 435)
Given a collection of intervals, find the minimum number of intervals to remove to make the rest non-overlapping. Sort by end time (greedy). Keep track of the last end. If current start < last end, it overlaps and we remove it (increment count). Otherwise, update last end. O(n log n) time, O(1) space.
non_overlapping_intervals.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
deferaseOverlapIntervals(intervals):
ifnot intervals:
return0
intervals.sort(key=lambda x: x[1])
count = 0
last_end = intervals[0][1]
for start, end in intervals[1:]:
if start < last_end:
count += 1else:
last_end = end
return count
Output
1 for [[1,2],[2,3],[3,4],[1,3]]
⚠ Greedy Choice
🎯 Key Takeaway
For minimum removals, always keep the interval that ends earliest.
● Production incidentPOST-MORTEMseverity: high
The Overlapping Calendar Bug
Symptom
Users saw overlapping meetings on their calendar, causing confusion and missed appointments.
Assumption
The developer assumed intervals were already sorted and non-overlapping.
Root cause
The merge logic didn't handle intervals that start at the same time or are completely contained within another.
Fix
Updated the merge algorithm to sort by start time and properly extend the end time when overlapping.
Key lesson
Always sort intervals by start time before merging.
Handle edge cases like equal start times and fully contained intervals.
Test with intervals that touch (e.g., [1,2] and [2,3]) – they should not merge unless specified.
Use a list to build the result incrementally.
Production debug guideSymptom to Action3 entries
Symptom · 01
Overlapping intervals not merged correctly
→
Fix
Check sorting order and merge condition (current.start <= last.end).
Symptom · 02
Missing intervals in output
→
Fix
Ensure you add the last interval after the loop.
Symptom · 03
Incorrect intersection results
→
Fix
Verify you're taking max of starts and min of ends, and only add if start <= end.
★ Quick Debug Cheat SheetCommon interval issues and fixes
Merge misses some overlaps−
Immediate action
Check sort by start time
Commands
intervals.sort(key=lambda x: x[0])
if current_start <= last_end: merge
Fix now
Update merge condition to include equality if needed.
Insert interval not placed correctly+
Immediate action
Iterate and compare with new interval
Commands
for interval in intervals:
if interval[1] < new_start: add; elif interval[0] > new_end: add new then rest; else merge
Fix now
Handle three cases: before, after, overlapping.
Meeting rooms count wrong+
Immediate action
Use min-heap for end times
Commands
heap = []; for start, end in intervals:
if heap and heap[0] <= start: heapq.heappop(heap); heapq.heappush(heap, end)
Fix now
Return len(heap) as number of rooms.
Problem
Time Complexity
Space Complexity
Key Technique
Merge Intervals
O(n log n)
O(n)
Sort and merge
Insert Interval
O(n)
O(n)
Linear scan with three cases
Meeting Rooms
O(n log n)
O(1)
Sort and check overlap
Meeting Rooms II
O(n log n)
O(n)
Min-heap for end times
Interval Intersection
O(m+n)
O(k)
Two pointers
Non-overlapping Intervals
O(n log n)
O(1)
Greedy by end time
⚙ Quick Reference
6 commands from this guide
File
Command / Code
Purpose
merge_intervals.py
def merge(intervals):
1. Merge Intervals
insert_interval.py
def insert(intervals, newInterval):
2. Insert Interval
meeting_rooms.py
def canAttendMeetings(intervals):
3. Meeting Rooms (Leetcode 252)
meeting_rooms_ii.py
def minMeetingRooms(intervals):
4. Meeting Rooms II (Leetcode 253)
interval_intersection.py
def intervalIntersection(A, B):
5. Interval List Intersections (Leetcode 986)
non_overlapping_intervals.py
def eraseOverlapIntervals(intervals):
6. Non-overlapping Intervals (Leetcode 435)
Key takeaways
1
Sorting by start time is the first step for most interval problems.
2
Use min-heap for problems requiring tracking of earliest end times.
3
Two-pointer technique works well when both lists are sorted.
Using wrong merge condition (e.g., using < instead of <=).
×
Forgetting to add the last interval after the loop.
INTERVIEW PREP · PRACTICE MODE
Interview Questions on This Topic
Q01JUNIOR
Given a list of intervals, merge all overlapping intervals.
Q02SENIOR
Find the minimum number of conference rooms required.
Q03SENIOR
Given two lists of intervals, find their intersection.
Q01 of 03JUNIOR
Given a list of intervals, merge all overlapping intervals.
ANSWER
Sort by start time, then iterate and merge if current start <= last end. Add the last interval after loop.
Q02 of 03SENIOR
Find the minimum number of conference rooms required.
ANSWER
Sort by start time, use a min-heap to track end times. For each meeting, if the earliest ending meeting ends before or at the current start, pop it. Push current end. Heap size is answer.
Q03 of 03SENIOR
Given two lists of intervals, find their intersection.
ANSWER
Use two pointers. For each pair, compute max start and min end. If start <= end, add to result. Advance the pointer with smaller end.
01
Given a list of intervals, merge all overlapping intervals.
JUNIOR
02
Find the minimum number of conference rooms required.
SENIOR
03
Given two lists of intervals, find their intersection.
SENIOR
FAQ · 3 QUESTIONS
Frequently Asked Questions
01
What is the most common interval problem?
Merge Intervals is the most common. It forms the basis for many other problems like Insert Interval and Meeting Rooms.
Was this helpful?
02
How do I handle intervals that touch (e.g., [1,2] and [2,3])?
It depends on the problem. Usually, touching intervals are not considered overlapping. In merge problems, they are often merged if the condition is start <= last_end. Clarify with the interviewer.
Was this helpful?
03
What is the time complexity of interval problems?
Most interval problems require sorting, so O(n log n) time. Space is typically O(n) for output, but can be O(1) if sorting in-place.