Coding Pattern:
Intervals
This pattern has a cheat sheet you can unlock.
Pattern concept
1 / 12
Use ← → arrow keys
Code snippets
# Returns whether two intervals overlap.
def is_overlapping(interval_a: List[int],
interval_b: List[int]) -> bool: a_start, a_end = interval_a[0], interval_a[1]
b_start, b_end = interval_b[0], interval_b[1]
if a_start < b_start and a_end < b_start:
# Interval a starts and ends in front of interval b.
return False
elif b_start < a_start and b_end < a_start:
# Interval b starts and ends in front of interval a.
return False
else:
# Interval a and b overlap in some way.
return True
# Example of how to sort intervals.
def sort_intervals():intervals = [[1, 3], [4, 5], [0, 7]]
intervals.sort(key=lambda x: x[0])
print(intervals) # Returns [[0, 7], [1, 3], [4, 5]]
intervals.sort(key=lambda x: x[1])
print(intervals) # Returns [[1, 3], [4, 5], [0, 7]]
# Get the intersection of two intervals.
def get_intersection(interval_a: List[int],
interval_b: List[int]) -> List[int]: a_start, a_end = interval_a[0], interval_a[1]
b_start, b_end = interval_b[0], interval_b[1]
return [max(a_start, b_start), min(a_end, b_end)]
# Merge two intervals together.
def get_merged(interval_a: List[int],
interval_b: List[int]) -> List[int]: a_start, a_end = interval_a[0], interval_a[1]
b_start, b_end = interval_b[0], interval_b[1]
return [min(a_start, b_start), max(a_end, b_end)]
How to identify
Does the problem involve any of these?
- Finding overlapping intervals
- Meeting Rooms I: Find whether there are overlapping intervals.
- Interval List Intersections: Find the intersection of intervals.
- Rearranging or updating a list of intervals, or building a schedule that fits a condition
- Insert Interval: Insert a new interval into a sorted list of intervals.
- Merge Intervals: Merge all overlapping intervals.
Note
Most interval problems take one pass through the list, which is O(n) time. If you need to sort the intervals first, the total becomes O(n log n).