Skip to content

Intervals

Reach for it when the problem says

  • Meetings
  • overlapping ranges
  • insert a range
Solved
0/30Solved
Problems
30Problems
Variants
6Variants

Problems

6 variants

Overlap checks

0 of 4 solved

Merge and insert

0 of 7 solved

Interval scheduling

0 of 7 solved

Sweep line

0 of 5 solved

Ranges and gaps

0 of 4 solved

Difference arrays

0 of 3 solved

Pattern 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.

Sort by start, then sweep and merge
0123456789
[6, 8]■■■
[1, 3]■■■
[2, 4]■■■
[7, 9]■■■

Unsorted, overlaps are scattered: [6, 8] overlaps [7, 9], which sits three rows away. Comparing all pairs would be O(n²).

1/4
Quick check
After sorting by start, why does a new interval only need to be compared with the last merged interval?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat 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

ConstraintWhat it tells you
n <= 10^4 to 10^5 intervalsO(n²) pair checks are too slow. Sort once: O(n log n).
Coordinates up to 10^9You cannot index an array by time. Sort the endpoints instead.
Coordinates up to 10^3 to 10^6, or a fixed year rangeA difference array or reach table indexed by position is fine and avoids sorting.
At most 1000 calls to a methodA 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 the pairs0/6 matched

Match each prompt phrase to the sub-pattern it usually points to.

Choose an item, then its match on the other side.

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.

Interval List Intersections: advance the one that ends first
[0,2]
0
↑i
[5,10]
1
[13,23]
2
j = [1,5]piece = [1,2]

Compare [0, 2] with [1, 5]: overlap is [max(0, 1), min(2, 5)] = [1, 2]. [0, 2] ends first, so advance i.

1/3
Python
def overlaps(a: list[int], b: list[int]) -> bool: return a[0] <= b[1] and b[0] <= a[1] def any_overlap(intervals: list[list[int]]) -> bool: intervals = sorted(intervals) return any(intervals[i][0] < intervals[i - 1][1] for i in range(1, len(intervals))) print(overlaps([1, 5], [5, 8]))print(any_overlap([[7, 10], [2, 4]]))print(any_overlap([[0, 30], [5, 10], [15, 20]]))
Output
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.

Insert Interval: insert [4, 8] into a sorted, disjoint list
12345678910
existing■■■■■■■■■■
new■■■■■
result

Existing: [1, 2], [3, 5], [6, 7], [8, 10] (they touch, so the row looks solid). New: [4, 8].

1/4
Python
def merge(intervals: list[list[int]]) -> list[list[int]]: merged: list[list[int]] = [] for start, end in sorted(intervals): if merged and start <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], end) else: merged.append([start, end]) return merged print(merge([[1, 3], [2, 6], [8, 10], [15, 18]]))print(merge([[1, 10], [2, 3]]))
Output
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.

Predict the outputPython

What does this print?

merged = [[1, 10]]
start, end = 2, 3
if start <= merged[-1][1]:
  merged[-1][1] = end
print(merged)
Need a nudge? Hints walk you through it.

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.

Missing Ranges with sentinels: nums = [0, 1, 3, 50, 75], range [0, 99]
-1
0
0
1
1
2
3
3
50
4
75
5
100
6

Add sentinels lower - 1 = -1 and upper + 1 = 100 (dimmed). Now every gap is between two neighbours.

1/4
Python
def gaps(intervals: list[list[int]]) -> list[list[int]]: shifts = sorted(intervals) free: list[list[int]] = [] busy_until = shifts[0][1] for start, end in shifts[1:]: if start > busy_until: free.append([busy_until, start]) busy_until = max(busy_until, end) return free print(gaps([[1, 3], [6, 7], [2, 4], [2, 5], [9, 12]]))
Output
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.

Non-overlapping Intervals: sort by end, keep what fits
12345678910
[2, 3]■■
[4, 5]■■
[6, 7]■■
[1, 10]■■■■■■■■■■

Sorted by end, the long [1, 10] comes last. Sorted by start it would come first and block everything.

1/3
Python
def max_non_overlapping(intervals: list[list[int]]) -> int: kept = 0 last_end = float("-inf") for start, end in sorted(intervals, key=lambda iv: iv[1]): if start >= last_end: kept += 1 last_end = end return kept ivs = [[1, 10], [2, 3], [4, 5], [6, 7]]print(max_non_overlapping(ivs), "kept,", len(ivs) - max_non_overlapping(ivs), "removed")
Output
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.

Quick check
To keep the most non-overlapping intervals, which sort makes the greedy correct?
Need a nudge? A hint rules out a wrong answer.

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.

Meeting Rooms II as events: [[0, 30], [5, 10], [15, 20]]
0:+1
0
5:+1
1
10:-1
2
15:+1
3
20:-1
4
30:-1
5

Each meeting becomes a start event and an end event, sorted by time.

1/4
Python
def peak_overlap(intervals: list[list[int]]) -> int: events = [] for start, end in intervals: events.append((start, 1)) events.append((end, -1)) events.sort() active = best = 0 for _, change in events: active += change best = max(best, active) return best print(peak_overlap([[0, 30], [5, 10], [15, 20]]))print(peak_overlap([[1, 5], [5, 10]]))
Output
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.

Range Addition: length 5, updates [1, 3, +2] and [2, 4, +3]
0
0
0
1
0
2
0
3
0
4
0
5

A difference array with one extra slot, so end + 1 always fits.

1/4
Python
def apply_updates(length: int, updates: list[list[int]]) -> list[int]: diff = [0] * (length + 1) for start, end, inc in updates: diff[start] += inc diff[end + 1] -= inc out, running = [], 0 for i in range(length): running += diff[i] out.append(running) return out print(apply_updates(5, [[1, 3, 2], [2, 4, 3], [0, 2, -2]]))
Output
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 it in order5 steps

Put the questions in the order you should ask them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 max when 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] and shifts[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.

Quick check
Remove Covered Intervals on [[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?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
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 +1 and -1 events, sort them, and track a running count to find the peak overlap.
Difference array
Record +v at a range's start and -v just after its end, then prefix sum once to apply every range update.