Intervals
Reach for it when the problem says
- Meetings
- overlapping ranges
- insert a range
- Solved
- 0/30Solved
- Problems
- 30Problems
- Variants
- 6Variants
Problems
6 variantsOverlap checks
0 of 4 solved- Meeting RoomsUp nextDeep diveEasyDecode Meeting Rooms
- Determine if Two Events Have ConflictDeep diveEasyDecode Determine if Two Events Have Conflict
- My Calendar IDeep diveMediumDecode My Calendar I
- Interval List IntersectionsDeep diveMediumDecode Interval List Intersections
Merge and insert
0 of 7 solved- Teemo AttackingEasyDecode Teemo Attacking
- Points That Intersect With CarsEasyDecode Points That Intersect With Cars
- Merge IntervalsSprintDeep diveMediumDecode Merge Intervals
- Insert IntervalSprintDeep diveMediumDecode Insert Interval
- Remove Covered IntervalsDeep diveMediumDecode Remove Covered Intervals
- Count Ways to Group Overlapping RangesDeep diveMediumDecode Count Ways to Group Overlapping Ranges
- Data Stream as Disjoint IntervalsDeep diveHardDecode Data Stream as Disjoint Intervals
Interval scheduling
0 of 7 solved- Non-overlapping IntervalsEssentialsDeep diveMediumDecode Non-overlapping Intervals
- Minimum Number of Arrows to Burst BalloonsEssentialsSprintDeep diveMediumDecode Minimum Number of Arrows to Burst Balloons
- Maximum Length of Pair ChainMediumDecode Maximum Length of Pair Chain
- Maximum Number of Events That Can Be AttendedMediumDecode Maximum Number of Events That Can Be Attended
- Video StitchingMediumDecode Video Stitching
- Maximum Profit in Job SchedulingDeep diveHardDecode Maximum Profit in Job Scheduling
- Minimum Number of Taps to Open to Water a GardenDeep diveHardDecode Minimum Number of Taps to Open to Water a Garden
Sweep line
0 of 5 solved- Meeting Rooms IIDeep diveMediumDecode Meeting Rooms II
- Divide Intervals Into Minimum Number of GroupsMediumDecode Divide Intervals Into Minimum Number of Groups
- My Calendar IIMediumDecode My Calendar II
- My Calendar IIIDeep diveHardDecode My Calendar III
- Minimum Interval to Include Each QueryDeep diveHardDecode Minimum Interval to Include Each Query
Ranges and gaps
0 of 4 solved- Summary RangesSprintDeep diveEasyDecode Summary Ranges
- Missing RangesDeep diveEasyDecode Missing Ranges
- Count Days Without MeetingsDeep diveMediumDecode Count Days Without Meetings
- Employee Free TimeDeep diveHardDecode Employee Free Time
Difference arrays
0 of 3 solvedPattern guide
Calendars, booking systems, video timelines, IP ranges, shift rotas: real data is full of [start, end] pairs, and interviewers love them because one small decision (what to sort by, whether touching counts) separates a clean O(n log n) answer from a buggy O(n²) one. This page is the map of the whole category: how to spot an interval problem, which of six shapes it takes, and the template for each.
What it is
An interval is a pair [start, end] describing a stretch of a line: time, positions, numbers. Interval problems ask how a set of these stretches relate to each other. Do any overlap? What is their union? How many cover one point? Which subset can coexist?
The pattern is almost always the same two moves: sort, then sweep left to right once while keeping a tiny bit of state (the last merged interval, the last kept end, a running count). Sorting is what makes it work. Once intervals are in start order, an interval can only interact with the ones just before it, so you never need to compare every pair.
Watch it on a timeline. Each row is an interval, each column a moment from 0 to 9.
Unsorted, overlaps are scattered: [6, 8] overlaps [7, 9], which sits three rows away. Comparing all pairs would be O(n²).
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
"pairs [start, end]", "meetings", "bookings", "ranges" | It is an interval problem. Decide what to sort by. |
| "overlap", "conflict", "clash", "intersect" | Overlap checks: the test a_start <= b_end and b_start <= a_end. |
| "merge", "union", "covered by at least one", "total length" | Merge and insert: sort by start, extend the last group. |
| "missing", "free time", "gaps", "summarise as ranges" | Ranges and gaps: merge, then read off the holes. |
| "minimum to remove", "maximum you can attend", "fewest arrows", "minimum to cover" | Interval scheduling: a greedy by end time, or a cover greedy. |
| "minimum rooms", "at the same time", "how many overlap at once" | Sweep line: +1 at start, -1 at end, track the peak. |
"add x to every element from i to j", "after all updates" | Difference array: two marks per update, one prefix sum at the end. |
Constraint clues
| Constraint | What it tells you |
|---|---|
n <= 10^4 to 10^5 intervals | O(n²) pair checks are too slow. Sort once: O(n log n). |
Coordinates up to 10^9 | You cannot index an array by time. Sort the endpoints instead. |
Coordinates up to 10^3 to 10^6, or a fixed year range | A difference array or reach table indexed by position is fine and avoids sorting. |
At most 1000 calls to a method | A linear scan per call is acceptable in a design problem. |
Input and output shape clues
- Input is a list of pairs, or two parallel lists of starts and ends, or a stream of
book(start, end)calls. - Output is a boolean (any overlap?), a list of intervals (merged, intersected, gaps), a count (rooms, removals, arrows), or an array of totals (range updates).
- A count of "how many at once" is a sweep. A list of "which ones survive" is a merge or a greedy.
Looks like it but isn't
- Sliding window. Both talk about ranges, but a sliding window is a contiguous stretch of one array. Interval problems hand you many separate ranges that you sort and sweep.
- Greedy in general. Interval scheduling is a greedy, but its proof depends on sorting by end. If the intervals carry different weights (Maximum Profit in Job Scheduling), the greedy breaks and you need dynamic programming.
- Graphs. Overlapping intervals form components, so union-find seems natural, but building the edges is O(n²). Sorting makes each component a contiguous run.
- Prefix sums. Difference arrays are their mirror image. If you only read ranges, use prefix sums. If you write to ranges, use a difference array.
Match each prompt phrase to the sub-pattern it usually points to.
The sub-patterns
Overlap checks
Use this when the question is whether two intervals (or any pair in a set) overlap, or what their shared part is. The one formula to know: [a1, a2] and [b1, b2] overlap when a1 <= b2 and b1 <= a2. For half-open intervals or "touching is fine", use <. The overlap itself is [max(a1, b1), min(a2, b2)] when that is non-empty.
For a whole list, sort by start and compare each interval with the previous one. For two sorted lists, walk both with one index each and advance whichever interval ends first.
Compare [0, 2] with [1, 5]: overlap is [max(0, 1), min(2, 5)] = [1, 2]. [0, 2] ends first, so advance i.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(1) for a pair, O(n log n) for a list, O(n + m) for two sorted lists. Problems: Meeting Rooms, Determine if Two Events Have Conflict, My Calendar I, Interval List Intersections.
Merge and insert
Use this when the answer is the union of the intervals: merged groups, their total length, how many groups there are, or the result of adding one more interval. Sort by start, keep the current group, and either extend it (end = max(end, new_end)) or close it and start a new one.
Insert Interval is the sorted special case: copy what ends before the new interval, fold in everything that overlaps it, copy the rest. No re-sort needed. Remove Covered Intervals and Count Ways to Group Overlapping Ranges are the same sweep with a different thing recorded at each step.
Existing: [1, 2], [3, 5], [6, 7], [8, 10] (they touch, so the row looks solid). New: [4, 8].
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) time for the sort, O(n) for the output. Insert Interval is O(n). Problems: Merge Intervals, Insert Interval, Teemo Attacking, Data Stream as Disjoint Intervals.
What does this print?
merged = [[1, 10]] start, end = 2, 3 if start <= merged[-1][1]: merged[-1][1] = end print(merged)
Ranges and gaps
Use this when the answer is what the intervals leave out: missing numbers, free time, days without meetings, or a compact summary of runs. Merge (or walk the already-sorted input), then read the answer from the space between consecutive groups. Sentinels at lower - 1 and upper + 1 remove the special cases at the ends.
Add sentinels lower - 1 = -1 and upper + 1 = 100 (dimmed). Now every gap is between two neighbours.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) when you must sort, O(n) when the input is already sorted. Problems: Summary Ranges, Missing Ranges, Employee Free Time, Count Days Without Meetings.
Interval scheduling
Use this when you choose a subset: keep the most non-overlapping intervals, remove the fewest, hit every interval with the fewest points, or cover a target range with the fewest intervals. The rule for keeping the most is sort by end and take each interval that starts after the last one kept. Ending earliest leaves the most room, so the greedy is optimal.
Two cousins live here. Covering (Video Stitching, taps in a garden) extends coverage as far as possible each step, which is Jump Game II. Weighted scheduling (Maximum Profit in Job Scheduling) breaks the greedy and needs DP over end-sorted jobs with binary search.
Sorted by end, the long [1, 10] comes last. Sorted by start it would come first and block everything.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n log n) for the sort. Weighted scheduling is also O(n log n) with binary search. Problems: Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons, Maximum Length of Pair Chain, Maximum Profit in Job Scheduling.
Sweep line
Use this when you need how many intervals cover a point at the busiest moment: rooms, groups, platforms, k-bookings. Turn each interval into two events, +1 at its start and -1 at its end, sort them, and walk them with a running count. The peak is the answer. Tie-breaking is where bugs hide: if a meeting ending at 10 frees a room for one starting at 10, process the end first.
The sweep also has a heap form: sort by start and keep a min-heap of active end times. That same structure answers "smallest active interval" queries (Minimum Interval to Include Each Query) when you sweep over sorted queries.
Each meeting becomes a start event and an end event, sorted by time.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Sorting (time, change) tuples puts -1 before +1 at the same time, which is the half-open rule. For inclusive intervals, put the -1 at end + 1 instead.
Complexity: O(n log n) time, O(n) space. Problems: Meeting Rooms II, Divide Intervals Into Minimum Number of Groups, My Calendar III, Minimum Interval to Include Each Query.
Difference arrays
Use this when every interval writes to a range of a small, indexable line: add seats to flights first..last, add inc to indices start..end, count people alive per year. Instead of touching every cell, write +v where the range starts and -v just after it ends. One prefix sum at the end turns the marks into totals. It is the sweep line with the sort replaced by array indexing.
A difference array with one extra slot, so end + 1 always fits.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n + k) for k updates on a line of length n, O(n) space. Problems: Range Addition, Corporate Flight Bookings, Maximum Population Year.
A decision checklist
When an interval problem lands in front of you, ask these questions in this order.
Put the questions in the order you should ask them.
- Tap the steps below in the right order.
Traps
- Touching endpoints.
[1, 5]and[5, 8]: merged in Merge Intervals, allowed in Meeting Rooms, intersecting in Divide Intervals Into Groups, sharing an arrow in Burst Balloons. Read the prompt and say your choice out loud. - Forgetting
maxwhen extending.[1, 10]then[2, 3]must stay[1, 10]. - Sorting by the wrong key. Merging wants start. Keeping the most wants end. Remove Covered Intervals wants start ascending and end descending on ties.
- Mutating input while iterating. Sort a copy (
sorted(...),[...arr].sort) unless the problem says in place is fine, especially in class-based problems where the caller keeps the list. - Overflowing comparators. In languages with fixed-width ints,
(a, b) => a[0] - b[0]overflows near±2^31. Compare instead of subtracting. - Tie order in a sweep. Ends before starts for half-open intervals. For inclusive ones, end at
end + 1. - Empty input.
merged[-1]andshifts[0]crash on an empty list. Check the constraints.
Always test: an empty list, one interval, identical intervals, touching intervals, one interval that contains the rest, and unsorted input.
[[1, 2], [1, 4], [3, 4]] sorts by start only (ties keep input order) and counts an interval when its end beats the max end so far. What goes wrong?How to talk it through
- Interval
- A pair
[start, end]describing a stretch of a line. Closed intervals include both ends; half-open[start, end)excludes the end. - Overlap test
- Two intervals overlap when
a_start <= b_end and b_start <= a_end. Use<when touching does not count. - Merge sweep
- Sort by start, then extend the last group with
max(end, new_end)or start a new group. - Activity selection
- Keep the most non-overlapping intervals by sorting by end and taking each one that starts after the last kept end.
- Sweep line
- Turn intervals into
+1and-1events, sort them, and track a running count to find the peak overlap. - Difference array
- Record
+vat a range's start and-vjust after its end, then prefix sum once to apply every range update.