Intervals Coding Interview: A Reasoning-First Guide
Learn to reason through intervals coding interview problems out loud: name the problem shape, choose what to sort, justify the greedy choice and state complexity clearly.
When an intervals coding interview question lands in front of you, work through four moves out loud: name what the intervals represent, decide whether order matters, pick the sort key that fits the output, and justify it before you write code. Then state the cost in one sentence. That sequence is what interviewers are listening for, and it works on a problem you have never seen, not just one you have rehearsed.
Why Interval Questions Keep Appearing
Intervals are a compact way to test whether you can model real scheduling, resource and range problems. A pair of numbers can stand for a meeting on a calendar, a block of memory, a numeric range in a dataset or a window of time in a log. The interviewer gets to watch you translate a plain-English situation into a structure you can reason about.
They also reward clear reasoning more than obscure knowledge: the core ideas are sorting, comparing endpoints and tracking a small amount of state. What matters is whether you can handle overlapping cases, boundary conditions and follow-up constraints without panicking. Treat the question as a reasoning exercise, not a template to recite, and you will sound like someone who can be trusted with a real scheduling problem.
The Four Interval Shapes to Recognise
Most intervals coding interview questions you meet are one of four shapes. Naming the shape early tells you what to sort and what state to keep.
- Merge: combine overlapping ranges into a clean set. Sort by start and extend the running end.
- Insert: place one new range into an already sorted list. Three phases: before, overlapping, after.
- Select: choose the largest set of non-overlapping ranges. Sort by end and take the earliest finish each time.
- Sweep: count how many ranges are active at once, as with meeting rooms. Walk start and end events with a running counter.
Start by Naming the Shape of the Problem
Before you touch code, spend thirty seconds asking what the intervals actually represent. Are they time ranges, numeric ranges, memory blocks or calendar events? The answer tells you what "overlap" means in this specific problem.
Next, ask what the output is. It might be a boolean (do any two overlap?), a count (how many can we schedule?), a merged list, a minimum number of resources, or a selected subset. The output shape usually hints at the algorithm family.
Then pin down the boundary rules. Are endpoints inclusive or exclusive? Do intervals that touch at a single point count as overlapping? Candidates often lose time on these two questions rather than on the algorithm.
Restate the question in your own words before writing anything. A short paraphrase like "so I need the fewest rooms that can hold every meeting, and meetings that end exactly when another starts can share a room" catches most misreadings. Finally, note the input guarantees: sorted or unsorted, distinct or duplicated, empty input allowed. Each guarantee either removes work or adds a case you must handle.
The Two Questions That Decide Your Approach
Once you know the shape, two questions narrow the field fast. In an intervals coding interview, asking them out loud also shows the interviewer how you think.
Question one: does the answer depend on the order of the intervals? If yes, sorting is usually the first move. If the answer is genuinely order-independent, sorting may only be a convenience, and a hash-based approach might be cleaner. For a plain yes-or-no overlap check, you often need no sort at all: track the furthest end seen so far and compare each new start against it in one pass.
Question two: when two intervals overlap, what is the smallest piece of information you need to keep? Usually it is a single endpoint — the furthest end you have reached, or the earliest end you have committed to. Naming that piece of state out loud is often the moment the solution clicks.
Work through a tiny example by hand. Take three or four intervals, draw them on a line, and write down what you tracked as you moved left to right. If you needed only one number, say so. That observation is the seed of the algorithm.
Before optimising, explain why brute force is too slow. For intervals, comparing every pair is O(n²), which is fine for ten intervals and hopeless for a million. Saying that out loud shows you understand the cost, not just the trick.
Sorting by Start: Merging and Insertion
Merging overlapping intervals is the canonical example. Sort by start, then walk through the list. Keep a running merged interval. When the next start falls within the running interval's end, extend that end to whichever end is larger. Otherwise, close the running interval and start a new one.
The greedy claim deserves a precise justification. After sorting by start, the running interval is the union of all intervals merged so far. If the next start is within the current end, that union is a single contiguous range, so extending the end to the maximum of the two ends is exactly correct — nothing between them is left uncovered. That is why committing to the merge is safe.
Inserting a new interval into a sorted list uses the same instinct in three phases. Copy every interval that ends before the new one starts. Absorb every interval that overlaps the new one, widening its start and end as you go. Then copy the rest. The phases are easy to narrate, which is exactly what an interviewer wants to hear.
Call out the boundary decision explicitly. If one interval ends exactly where the next begins, do they merge? State your assumption — "I'll treat touching intervals as non-overlapping, but tell me if you want them merged" — and continue. In practice, narrate the boundary as a decision rather than a detail: say which comparison operator encodes your convention, note that the other convention flips that one operator, and move on.
Sorting by End: Selection and Scheduling
For selection problems, sort by end time instead. The classic pattern: take the interval that finishes earliest, then repeatedly take the next interval that starts at or after the last chosen end.
The justification is an informal exchange argument. Any schedule that picks a later-finishing interval can replace it with the earliest-finishing compatible one, which ends no later and so leaves at least as much room for the rest. You do not need a formal proof in the interview; you need that sentence.
"Maximum number of non-overlapping intervals" is exactly this selection pattern. "Minimum number of meeting rooms" is a related but distinct problem: it is not solved by the end-sort selection, but by sweeping over start and end events, keeping a running count of rooms in use and recording the maximum. The count goes up at a start and down at an end. Say that distinction out loud so you do not conflate the two.
The common mistake here is sorting by start for a selection problem. It produces a plausible answer that is often wrong, because starting early does not mean finishing early. If you catch yourself reaching for a start-sort, ask whether you are merging or selecting. Many intervals coding interview questions reward exactly that check.
Talking About Time and Space Complexity
State complexity in three beats: the sort, the pass, then the combination. Sorting is O(n log n). The sweep is a single pass, so O(n). Combined, the dominant term wins, so the total is O(n log n) time.
Be honest about space. If you build a new output list, that is O(n). You can claim O(1) extra only if you are allowed to overwrite the input array; otherwise the output list is O(n).
The plain meeting-rooms sweep needs only a counter, so its extra space is O(1). A heap belongs to a different variant, such as a maximum allowed overlap of k: sort by start, keep a min-heap of the end times of active intervals, pop intervals that have ended, and if the active count exceeds k the constraint is violated. If you use a heap, name the per-operation cost — O(log n) per push or pop — and note that with up to n of them that adds O(n log n), which combined with the sort keeps the total at O(n log n).
Practise a single sentence until it is automatic: "Sorting is O(n log n), the sweep is O(n), so the overall time is O(n log n); extra space is O(n) for the output list, or O(1) extra only if I'm allowed to overwrite the input." That sentence, delivered calmly, does more for your score than a fast but silent solution. It is the same habit that helps on any data structure question, where naming the cost of each operation is half the answer.
Reasoning Through a Variation You Have Not Seen
Interviewers often twist the problem once you have a working answer. Three common twists: weighted intervals, where each interval has a value and you want the best total; a maximum allowed overlap, where you can stack at most k intervals at once; and intervals on a circle, where the line wraps around.
For each twist, the first move is to reduce it to a known shape or explain precisely why the old greedy argument breaks. Weighted intervals break the earliest-finish rule because a short high-value interval may beat two long low-value ones; that pushes you toward dynamic programming, and saying so is a strong moment. Maximum overlap often becomes a sweep with a heap.
For circular intervals, a short correct sketch is enough. Pick one interval as a reference. Every valid selection either includes it or excludes it. Branch on those two cases, and reduce each branch to the linear problem you already know. The subtlety is that on a circle, "overlaps the reference" also covers intervals that cross the point where the line wraps around, so state that condition explicitly rather than assuming the linear rule carries over.
Here is how you might narrate the weighted twist out loud, using a small counterexample:
"Let me test the earliest-finish rule on a weighted case. I have [1, 4] worth 3, [2, 3] worth 2, and [5, 6] worth 3. Earliest finish picks [2, 3] first, then [5, 6], for a total of 5. But [1, 4] plus [5, 6] gives 6, which is better. So the greedy rule fails here: finishing early is not the same as finishing with the most value. That tells me I need to track the best total ending at each point, which points toward dynamic programming rather than a single sweep."
Before committing to a new greedy rule, test it against a small counterexample. Three intervals and a napkin sketch will usually tell you whether the rule survives. If it fails, say so plainly: "This greedy choice fails here, so I need a different state." That sentence signals maturity, not weakness.
If you get stuck, restate the invariant you are trying to maintain. "At every point, I want to know the furthest end I have committed to." Naming the invariant often reveals the missing case.
Practising Interval Reasoning Before Interview Day
Every intervals coding interview question you practise is a chance to rehearse the reasoning path, not to recall an answer. Work in timed sets of two or three problems, narrating every step as if someone were listening. The narration is the skill; the code is the artifact.
Record yourself and review where the explanation went quiet or jumped a step. Candidates often skip the justification for the greedy choice, and it is usually the part that separates a memorised answer from a reasoned one. Listen especially for the boundary decision: did you say which convention you were using, or did you let it pass silently?
Re-solve each problem a day later from a blank page. If you can derive the approach again, the reasoning stuck. If you can only recall the code, you memorised a template and it will not survive a variation.
Use a small set of interval problems and vary the constraints yourself: make the input sorted, add duplicates, allow touching endpoints, ask for the k-th selection. Each variation forces you to re-derive rather than recall.
Keep practice honest. The goal is to be able to derive the approach from the problem statement, not to reproduce a specific answer you saw once. If you are returning to algorithm practice after time away, the narration skills here overlap with what you would use on other data structures; see our guides on Hash Maps Coding Interview: How to Explain Your Reasoning and Sorting Coding Interview: Reason Through the Algorithm Out Loud. Pair this with broader concept review — for example Python Interview Questions: Concepts and Trade-Offs — and treat each session as a chance to explain your thinking more clearly than last time.
Before Your Next Interview
The takeaway: name the shape, pick the sort key, justify it in one sentence and state the cost. That sequence carries you through an intervals coding interview even when the problem is new. Next, record yourself solving one merge problem and one selection problem out loud, then listen back for the moment your explanation went quiet. Fix that moment first; the code will follow.
Frequently asked questions
Do I always need to sort intervals in a coding interview?
No, but sorting is the usual first move because many interval answers depend on order. Ask yourself whether the answer changes if you shuffle the input. If it does, sorting is probably the right starting point. If the answer is genuinely order-independent, a hash-based or counting approach may be simpler.
How do I decide whether to sort by start or by end?
Look at what you must produce. If you are reshaping the input into a merged or inserted list, sort by start so you can extend the running range. If you are choosing a subset, sort by end so the earliest finish is available first. Say the reason out loud before you sort.
What is the time complexity of merging overlapping intervals?
O(n log n) overall, because sorting dominates and the merge pass is a single O(n) scan; if the input is already sorted, it is O(n).
How do I handle intervals that touch at the endpoints?
Ask the interviewer which convention they want, in one line: "Should [1, 3] and [3, 5] count as overlapping?" The answer changes the output, not just the code. Under the overlapping convention they merge into [1, 5]; under the non-overlapping convention the result is [1, 3] and [3, 5]. Write the convention in a comment so your code and your explanation agree.
What should I say if I cannot see the greedy solution right away?
Say what you are trying to preserve as you move through the intervals, then try a candidate rule on three or four intervals and watch whether it holds. If it breaks, describe the extra information you would need to keep instead. Talking through the failure gives the interviewer something to follow and often leads you to the right state.
Are interval questions common for career changers and junior candidates?
They come up often, and they suit candidates who reason carefully rather than recall quickly, because the input is small and the logic is visible. If you are returning to practice, start with merging and selection, then add one boundary variation. The sorting and state-tracking habits carry over to other data structure questions.
Rehearse interval reasoning out loud with more practice guides on our blog.