Software interviews
Interval problems for coding interviews: merge, insert and overlap
An interval problem gives you ranges, such as meetings or bookings, and asks what happens when they overlap. Almost all of them yield to one move: sort by start, then sweep once. This page explains why that works, the signals that call for it, three patterns with worked problems and the edge cases an interviewer is likely to test. Five original problems have answers that a separate program recomputes.
Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.
Book your first hour ($250)What the technique is and what it costs
An interval has a start and an end. Two intervals overlap when each starts before the other ends. The trick that makes the whole family easy is sorting: once intervals are sorted by start, any interval that overlaps the current group must start no later than the group’s current end, so you only ever compare with the last thing you kept.
The cost has two parts. A comparison sort takes time proportional to n log n for n intervals, and one pass over the sorted list takes time proportional to n, so the total is O(n log n). For references, MIT OpenCourseWare’s 6.006 Introduction to Algorithms covers algorithms, data structures and the analysis of running time, and the NIST Dictionary of Algorithms and Data Structures defines the terms. If the input arrives already sorted, as in the insert problem below, one pass in O(n) is enough.
A brute-force version compares every pair of intervals, which takes O(n^2). Saying so out loud, and then saying how sorting removes the pairs, is a good way to open the answer.
The problem signals that call for it
Reach for intervals and sorting when you see these signs in a statement:
| Signal in the statement | What it usually means | Technique |
|---|---|---|
| “Merge the overlapping ranges” | Group ranges that touch or overlap | Sort by start, sweep, extend the current end |
| “Total time covered” or “total length” | Count overlap once | Merge, then add the lengths |
| “Fewest rooms,” “most at once” or “peak load” | The largest number live at one moment | Sort starts and ends separately and walk both |
| “Insert a range into a sorted list” | Three zones: before, overlapping, after | One pass over the sorted list |
| “How many pairs conflict” | Count overlapping pairs | Brute force, or sort and count the active ones |
| “Can one person attend all of them” | No two overlap | Sort by start and check neighbors |
Pattern 1: merging
Sort by start. Keep a current interval. For each next interval, if it starts at or before the current end, extend the current end to the larger of the two ends. Otherwise close the current interval and start a new one. The detail that interviews test is the tie: with closed intervals, one that starts exactly where the last ends is merged.
Here is a worked example. Our own problem 1 below has seven closed intervals and asks how many remain after merging. The sweep is short once sorted, and the answer comes from counting how many times the “starts after” case fires, plus one.
Problem 2 uses the same merge to find the total length covered. Merge first, then add the lengths of the merged intervals. Adding the original lengths overcounts, because every overlap is counted twice.
Pattern 2: counting what is live at once
Some problems do not need the merged intervals. They need the peak: how many meetings are happening at the same moment, which is also the fewest rooms that will do. Sort the starts and the ends as two separate lists. Walk through them with two pointers: when the next start comes before the next end, one more meeting is live, and otherwise one meeting has finished. Track the largest count.
Decide in advance what happens at a tie. If a meeting that ends at 11 and one that starts at 11 can share a room, the end must be handled first. That is the half-open convention, where an interval includes its start and excludes its end. Problem 3 uses it.
Pattern 3: inserting into a sorted list
When the list is already sorted and has no overlaps, you can add a new interval in one pass. Split the list into three zones: intervals that end before the new one starts, intervals that overlap it and intervals that start after it ends. Keep the first zone, merge the second into one interval from the smallest start to the largest end, and keep the third. Problem 4 is a worked example.
Edge cases interviewers probe
- Closed or half-open. Ask which one the problem means, and say what you assume. It changes whether a shared endpoint overlaps.
- An empty list. Return an empty result, and say so before you run the code.
- One interval inside another. The merged end must be the larger of the two ends, not the second one’s end.
- Intervals given unsorted. Sort first, and say the cost.
- Identical intervals. They overlap each other, so they merge into one.
- A new interval that touches the first or the last one, or lies completely before or after the list.
- Start equal to end. A zero-length interval is a point: decide whether it counts.
A good habit is to test your solution on the smallest tricky case you can write by hand, for example two intervals that share only an endpoint, before you call it done.
Five practice problems, in order of difficulty
These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from the basic merge to the sweep that counts pairs.
Problem 1. Closed intervals are given by their starts and ends. The starts are 1, 8, 2, 15, 6, 17, 10 and the ends, in the same order, are 3, 10, 6, 18, 7, 20, 12. Two intervals overlap if they share at least one point, including a single shared endpoint. After merging every group of intervals that overlap, directly or through a chain, how many intervals remain? Give an integer.
Show the answer and the working
Answer: 3
- Sort by start: [1, 3], [2, 6], [6, 7], [8, 10], [10, 12], [15, 18], [17, 20].
- Sweep once, keeping the current merged interval. [2, 6] starts at 2, which is at most 3, so it joins [1, 3] and the end becomes 6. [6, 7] starts at 6, which is at most 6, so the shared endpoint joins it: [1, 7].
- [8, 10] starts at 8, which is after 7, so it begins a new group. [10, 12] shares the endpoint 10 and joins it: [8, 12].
- [15, 18] starts after 12 and begins a third group, and [17, 20] starts at 17, which is at most 18, so it joins: [15, 20].
- Three merged intervals remain: [1, 7], [8, 12] and [15, 20]. The sort costs O(n log n) and the sweep costs O(n).
Problem 2. On a number line, six stretches run from their starts to their ends. The starts are 1, 4, 9, 12, 3, 20 and the ends, in the same order, are 5, 7, 11, 16, 6, 22. What is the total length covered by at least one stretch, counting any overlap once? Give an integer.
Show the answer and the working
Answer: 14
- Sort by start: [1, 5], [3, 6], [4, 7], [9, 11], [12, 16], [20, 22].
- The first three overlap and merge into [1, 7], which has length 6.
- [9, 11] has length 2, [12, 16] has length 4 and [20, 22] has length 2, and none of them touches another.
- The total is 6 + 2 + 4 + 2 = 14. Adding all six lengths gives 4 + 3 + 3 + 2 + 4 + 2 = 18, which counts 4 units of overlap twice.
Problem 3. Eight meetings have start times 9, 10, 11, 13, 12, 14, 9, 10 and end times 12, 11, 14, 15, 13, 16, 10, 13, in the same order, in whole hours. A meeting occupies its room from its start up to but not including its end, so one that ends at 11 and one that starts at 11 can share a room. What is the fewest rooms that can hold all eight meetings? Give an integer.
Show the answer and the working
Answer: 3
- The fewest rooms equals the most meetings that are live at the same moment, because meetings that overlap need separate rooms and no moment can need more than that.
- Sort the starts: 9, 9, 10, 10, 11, 12, 13, 14. Sort the ends: 10, 11, 12, 13, 13, 14, 15, 16. Walk both lists, adding one when a start comes before the next end and subtracting one otherwise. A tie sends the end first, because an ending meeting frees its room at that time.
- The count goes 1, 2 at hour 9, then back to 1 at hour 10 when the meeting from 9 to 10 ends, then up to 3 when two meetings start at 10, and it never goes above 3.
- A check at hour 11 finds the meetings 9 to 12, 10 to 13 and 11 to 14 live together, so 3 rooms are needed. The sort takes O(n log n) and the walk takes O(n).
Problem 4. A list of closed intervals that do not overlap has starts 1, 4, 8, 12, 16, 21 and ends 3, 6, 10, 14, 18, 23, in the same order. The closed interval from 5 to 13 is added, and every group of intervals that then overlap, including by a shared endpoint, is merged. How many intervals are in the final list? Give an integer.
Show the answer and the working
Answer: 4
- Split the list into three parts: intervals that end before 5, intervals that overlap [5, 13] and intervals that start after 13.
- [1, 3] ends before 5, so it stays. [4, 6], [8, 10] and [12, 14] each share a point with [5, 13], so they merge with it into one interval from the smallest start, 4, to the largest end, 14.
- [16, 18] and [21, 23] start after 13, so they stay.
- The final list is [1, 3], [4, 14], [16, 18] and [21, 23], which is 4 intervals. Because the list is sorted, one pass in O(n) does it.
Problem 5. Six bookings have start times 1, 3, 4, 8, 9, 11 and end times 5, 7, 6, 10, 12, 13, in the same order. A booking runs from its start up to but not including its end. How many pairs of bookings overlap, meaning they are both active at some moment? Give an integer.
Show the answer and the working
Answer: 5
- Two bookings overlap exactly when each one starts before the other one ends.
- The bookings are [1, 5), [3, 7), [4, 6), [8, 10), [9, 12) and [11, 13). The first three overlap in every pair: [1, 5) with [3, 7), [1, 5) with [4, 6) and [3, 7) with [4, 6). That is 3 pairs.
- Among the last three, [8, 10) overlaps [9, 12) and [9, 12) overlaps [11, 13), but [8, 10) ends before [11, 13) starts. That is 2 pairs.
- No booking of the first group reaches the second group, so the total is 5. Checking every pair costs O(n^2); sorting the starts and counting the bookings still active at each start does it in O(n log n).
Every answer above is recomputed by a separate program, which rebuilds each result by a different route from the written steps: a grouping of overlapping pairs, a marked number line, a count at every hour and a loop over all pairs. These are our own practice problems. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.
Questions
How do you merge overlapping intervals?
Sort the intervals by start, then sweep once, extending the current interval while the next one starts at or before its end. The sort costs O(n log n) and the sweep costs O(n).
How do you find the fewest meeting rooms?
The fewest rooms equals the most meetings that are live at the same moment. Sort the starts and the ends separately and walk both lists, adding one for a start and subtracting one for an end.
Do intervals that share an endpoint overlap?
It depends on whether they are closed or half-open, so ask before you code. Closed intervals that share an endpoint overlap, and half-open intervals that touch end to end do not.
How a session helps
A session with George is a place to code a problem aloud and have the reasoning questioned: why you sort, what you assume about the endpoints and which edge case you tested. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.
Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.