Quick revision
The short answer
Merging overlapping intervals is a sorting and intervals problem: sort by start, then sweep once. After sorting, we keep one open interval; a next interval that starts at or before its end extends it to the larger end, and a gap closes it for good, because everything later starts further right. Sorting costs O(n log n), the sweep O(n), and the result takes O(n) space.
The solution
What it costs
| Approach | Time | Extra space |
|---|---|---|
| Merge any overlapping pair, then search again | up to O(n^3) | O(n) |
| Sort by start, then sweep once | O(n log n) | O(n) |
| Sweep only, input already sorted by start | O(n) | O(n) for the result |
What to remember
We merged overlapping intervals by sorting them by start and sweeping once with a single open interval. An interval that starts at or before the open end stretches it to the larger end, and a gap closes it for good, because nothing later can reach back. The last open interval is added after the loop. That is O(n log n) time and O(n) space. The clue to remember is a list of ranges to merge or compare: sort by start, and the all-pairs question becomes a question about neighbours.
1What it means to merge overlapping intervals
Picture a long wooden ruler on a table, and a handful of strips of coloured tape that someone has stuck along it. One strip runs from the mark 1 to the mark 3, another from 2 to 6, another from 8 to 10, and the last from 15 to 18. If you stand back and look, you do not see four strips. Where two strips cross, the tape forms one unbroken stretch, so you see three taped stretches: 1 to 6, 8 to 10 and 15 to 18. That picture is the whole problem.
In the question each strip is an interval, a pair of numbers [start, end] with start no larger than end. Merging means replacing every group of intervals that share at least one point with a single interval that covers the whole group. The answer is the list of taped stretches you would see from across the room, and we hand it back sorted by start, left to right along the ruler.
Please do not be put off by the word interval. There is no new data structure here, only pairs of numbers and one comparison. The problem looks hard only because the strips arrive jumbled, and the trick will be to stop them being jumbled.
Let us keep one example for the whole article. We are given [[8, 10], [1, 3], [15, 18], [2, 6]]. Take each pair in turn and ask whether it shares a point with another. [1, 3] and [2, 6] both contain 2 and 3, so they overlap, and the stretch they cover together starts at the smaller start, 1, and ends at the larger end, 6. [8, 10] touches nothing else, and neither does [15, 18]. So the answer is [[1, 6], [8, 10], [15, 18]].
Each box is one interval written start-end. The two highlighted boxes share points, so they melt into one.
- input size
- 4 intervals
- answer
- [1,6] [8,10] [15,18]
1We are given 8-10, 1-3, 15-18 and 2-6. Only 1-3 and 2-6 share points (2 and 3), so they merge into 1-6, and the other two stay as they are.
What to assume
- Do intervals that only touch, such as [1, 4] and [4, 5], count as overlapping?
- We treat intervals as closed, meaning both end points belong to the interval, so the two share the point 4 and merge into [1, 5].
- Is the input sorted?
- We do not assume so, and we leave the caller's array as it was. An empty input gives an empty answer.
A careful candidate settles a few details before writing code. Do intervals that only touch, such as [1, 4] and [4, 5], count as overlapping? We treat intervals as closed, meaning both end points belong to the interval, so the two share the point 4 and merge into [1, 5]. Is the input sorted? We do not assume so, and we leave the caller's array as it was. An empty input gives an empty answer.
Your turn
Solve it before you read on. Above is one example with the result expected for it. Under What to assume are the points this solution takes as given. Say your approach aloud or type it below, and write the code in your own editor. Then take one hint at a time and compare.
2How to recognise a sorting and intervals problem
When a beginner first reads this question, the natural plan is to compare intervals with each other: take one, look through the rest for anything it overlaps, merge, and carry on. Notice the worry hiding inside that plan. After a merge, the new, wider interval may overlap something we already looked at and rejected. Because the intervals are in no particular order, any interval might overlap any other, and we never know when we are finished.
So let us read the question slowly and take its clues one at a time. The first clue is the phrase a list of intervals. Every item is a range on a number line, a stretch with a left edge and a right edge, and ranges have a natural order: from left to right along the ruler. Whenever the items of a problem have a natural order and the input does not respect it, sorting them is the first thing to consider.
The second clue is the word overlapping. Whether two ranges overlap depends on where their edges sit relative to each other, which is a question about order. A hash map, very good at asking whether we have seen this exact value before, cannot tell us that 2 lies inside [1, 3], so the tool many beginners reach for first does not help.
The third clue is the word merge. Merging is something we do with neighbours. If the strips of tape were already lined up by their left edges, a strip could only ever join the stretch just before it, because everything further left has already ended or has already been joined. So we would only ever need to look backwards one step.
Together these clues point to the sorting and intervals pattern. The name says exactly what we do: sort the intervals, usually by their start, and then sweep through them once from left to right, which means visiting each one in order and deciding its fate on the spot, keeping only a little information about what came before. The general rule to carry to new problems is that when the items are ranges that must be merged, compared or counted, sort them by start and the hard all-pairs question becomes an easy neighbour question.
A few patterns look similar but do not fit. A min-heap of end times, a structure that always hands back the earliest end, answers how many ranges are open at the same moment, the meeting rooms question, but merging needs only one open range at a time. Sorting by end suits the problem of removing the fewest intervals, but for merging it is sorting by start that keeps the open stretch growing only to the right.
3The honest first attempt, merging any two that overlap until none do
When we do not yet see a clever route, the honest first attempt follows the definition word for word. Look for any two intervals that overlap. If you find a pair, replace them with one interval from the smaller start to the larger end, and then start looking again from the beginning, because the list has changed. When a whole search finds no overlapping pair, we are done. This brute force is a perfectly good start, because it is obviously correct, and writing it down shows us where the cost hides.
First we need a test for whether two intervals p and q overlap. Two strips of tape fail to overlap only when one ends before the other begins. Turning that around, they overlap when p starts at or before q ends and q starts at or before p ends. On [1, 3] and [2, 6] that is 1 <= 6 and 2 <= 3, both true. On [1, 3] and [8, 10] the second test, 8 <= 3, is false, so they do not overlap.
Now let us run it by hand on [[8, 10], [1, 3], [15, 18], [2, 6]]. The search compares [8, 10] with each of the other three, finding nothing, then [1, 3] with [15, 18], nothing, and [1, 3] with [2, 6], a match. That was five comparisons. We merge them into [1, 6] and start again with [8, 10], [1, 6] and [15, 18], comparing all three pairs and finding nothing. In all, two searches and eight comparisons, and the result still has to be sorted.
Now let us count in general. One search compares every pair, and n intervals have n(n - 1) / 2 pairs, which grows like n squared. Each successful search removes one interval, so there can be up to n searches, and the worst case is O(n cubed), read as order n cubed. For a thousand intervals that is on the order of a billion comparisons. The extra space is O(n), for the working copy of the list.
So where exactly is the waste? Look at the second search in our example. It compared [8, 10] with [15, 18] again, a pair the first search had already checked and found apart, and nothing about those two had changed. The first attempt keeps asking questions it already knows the answers to, because after every merge it forgets everything and starts over.
It forgets because it has no sense of order. In a jumbled list, the interval that overlaps [1, 3] could be anywhere, so every search has to look everywhere. So let us ask the beginner's question that leads us forward. What if the strips were picked up from the ruler in order of their left edges? Would we still need to compare every pair?
4Getting to sort and sweep, one observation at a time
Suppose we sort the intervals by start, so the example becomes [[1, 3], [2, 6], [8, 10], [15, 18]]. On the ruler, this is like peeling the strips off and laying them down again one at a time, always taking the strip whose left edge is furthest left. Now think about what happens as we lay them down. The stretch we are currently taping either gets longer, because the next strip starts on top of it, or it is finished, because the next strip starts after a gap.
So we keep exactly one interval in hand, which we will call the open interval, or current in the code. It is the merge of everything seen since the last gap, the stretch of tape we are still laying. For each next interval there are only two cases. If next starts at or before current ends, they overlap, and we stretch current to end at whichever end is further right. Otherwise there is a gap, so current is finished: it goes into the result and next becomes the new open interval. After the last interval, the open interval goes into the result too.
A beginner rightly asks how we can be sure, when we see a gap and put current in the result, that no later interval will overlap it. Let us think with numbers. Current is [1, 6] and next is [8, 10], which starts at 8. Because the list is sorted by start, every interval after [8, 10] starts at 8 or later. Every one of them begins to the right of 6, so none of them can reach back to touch [1, 6]. Sorting is what makes it safe to close an interval and never look at it again, and that is why one pass is enough.
The second question a beginner asks is about the new end. When next overlaps current, why not simply set current's end to next's end, since next came later? Let us try it on a small case and see what goes wrong. The picture below uses the sorted intervals [1, 10], [2, 3] and [4, 5], where the second and third lie entirely inside the first.
Sorted input 1-10, 2-3, 4-5. The middle frame is the tempting mistake; the last frame is what the real code does.
- open
- 1-10
- check
- 2 <= 10, overlap
1The open interval is 1-10, and the next one, 2-3, starts at 2, which is at most 10. So they overlap, and we must decide the new end.
- open
- 1-3, wrong
- check
- 4 > 3, false gap
2Suppose we simply copy the next end. The open interval shrinks to 1-3, and then 4-5 looks like a gap, so we would wrongly report [1,3] and [4,5].
- open
- 1-10
- result
- [1,10]
3With
max(10, 3)the end stays 10, so 2-3 and then 4-5 are both swallowed, and the single answer is [1,10], which is what main prints.
Copying next's end shrank the open interval from [1, 10] to [1, 3], and then [4, 5] looked like a gap although it sits inside [1, 10]. An interval that starts later can still end earlier, because it may be completely contained in the open one. Taking the larger of the two ends, Math.max(current end, next end), means the open interval can only ever grow. This is the bug interviewers watch for most closely, and it is tempting precisely because on the usual example, where every later interval ends further right, the wrong code gives the right answer.
We test next start <= current end, with less than or equal, because under the closed convention [1, 4] and [4, 5] share the point 4 and must merge. For half-open intervals we would test next start < current end instead, and saying so aloud shows the interviewer we thought about it.
5Watching the sweep on the example
The picture below plays the method on [[8, 10], [1, 3], [15, 18], [2, 6]]. The first frame is the input as given, and the second is the same intervals sorted by start. From then on, the pointer i marks the interval we are deciding about, and the panel shows the open interval and the result after that step. Watch how each step compares only two numbers, the next start and the open end, and how an interval enters the result only at a gap or at the very end.
Each box is one interval, start-end. After the sort, watch the open interval in the panel grow or get closed, and the result list fill up.
- open
- nothing yet
- result
- none yet
1This is the list as we are given it. Neighbours in the list are not neighbours on the ruler: 8-10 sits before 1-3, and 2-6 is far from 1-3.
- open
- nothing yet
- result
- none yet
2We sort by start. Now 1-3 and 2-6, the two that overlap, sit side by side, and every interval only needs to be checked against the one before it.
- open
- 1-3
- result
- none yet
3The first interval, 1-3, becomes the open interval: the stretch of tape we are still laying and may still extend.
- open
- 1-6
- check
- 2 <= 3, overlap
- result
- none yet
4Next is 2-6. Its start 2 is at most the open end 3, so they overlap. The end becomes
max(3, 6)= 6, and the open interval is now 1-6.- open
- 8-10
- check
- 8 > 6, gap
- result
- [1,6]
5Next is 8-10. Its start 8 is greater than the open end 6, so there is a gap. 1-6 is finished, goes into the result, and 8-10 becomes the open interval.
- open
- 15-18
- check
- 15 > 10, gap
- result
- [1,6] [8,10]
6Next is 15-18. Its start 15 is greater than the open end 10, another gap. 8-10 goes into the result and 15-18 becomes the open interval.
- open
- closed
- result
- [1,6] [8,10] [15,18]
7The loop has run out of intervals, but 15-18 is still open, so we add it after the loop. The answer is [1,6] [8,10] [15,18].
Let us read the important frames back. In the fourth frame, 2-6 meets the open interval 1-3. The test is 2 <= 3, so they overlap, and the end becomes the larger of 3 and 6, which is 6. Nothing went into the result, because the next interval might extend 1-6 further.
In the fifth frame, 8-10 meets the open interval 1-6. The test 2 <= 3 has become 8 <= 6, which is false, so there is a gap. This is the moment where sorting earns its keep: everything still to come starts at 8 or later, so 1-6 is final and safe to put in the result.
The last frame is the step beginners most often forget. When the loop ends, the open interval 15-18 has not been added yet, because it only ever gets added when a gap closes it. So the code adds it after the loop. Leaving out that one line is the second most common bug in this problem, and it quietly drops the last stretch from every answer.
6The complete Java program
Here is the full program. The merge method takes an array of intervals, each a two-element int array {start, end}, and returns the merged intervals as a new array. main runs our example, the touching case, the contained case from the picture, and an empty input, and each comment shows what that line prints.
Let us read merge in the order it runs. The first line returns an empty array for an empty input, because the rest of the method begins by looking at the first interval. Next we clone the outer array and sort the copy, so the caller's array keeps its order. Comparator.comparingInt(iv -> iv[0]) tells the sort to order intervals by their start, iv[0].
Why not write the comparator as (a, b) -> a[0] - b[0]? Because subtracting two large int values can overflow, and then the sort silently orders them wrongly. comparingInt compares instead of subtracting, so it is always safe.
Then we create the result list, merged, and take the first sorted interval as the open interval, cloning it because we are about to change its end and must not change the caller's array through a shared reference. Inside the loop, if next[0] <= current[1], next starts at or before the open end, so Math.max(current[1], next[1]) stretches the end without ever shrinking it. Otherwise there is a gap, so merged.add(current) puts the finished interval into the result and current = next.clone() opens the next one.
After the loop, merged.add(current) adds the last open interval, the step from the final frame of the picture. Finally toArray turns the list back into an int[][]. So main prints [[1, 6], [8, 10], [15, 18]], then [[1, 5]] for the touching pair, then [[1, 10]] for the contained case, then [] for the empty input.
7How much it costs, and the cases at the edges
Let us count on the example first. After a handful of comparisons to sort four intervals, the sweep made one comparison for each of the three intervals after the first. For n intervals, Java's sort takes O(n log n) time, roughly n times the number of times you can halve n; for a thousand intervals that is about ten thousand steps rather than a million. The sweep then does one comparison per interval, O(n). The sort is the larger part, so the total is O(n log n).
For space, the sorted copy of the outer array holds n references, and the result can hold up to n intervals when nothing overlaps, so the extra space is O(n). If the input already arrives sorted by start, we can skip the sort and the time drops to O(n), with the sweep alone doing the work.
| Approach | Time | Extra space |
|---|---|---|
| Merge any overlapping pair, then search again | up to O(n^3) | O(n) |
| Sort by start, then sweep once | O(n log n) | O(n) |
| Sweep only, input already sorted by start | O(n) | O(n) for the result |
Now the edge cases, one at a time. An empty input returns an empty array from the first line, so we never touch sorted[0]. A single interval opens as current, the loop does not run, and it is added after the loop, so it comes back unchanged. Two intervals that only touch, like [1, 4] and [4, 5], pass the test 4 <= 4 and merge into [1, 5], as main shows.
An interval contained in another, like [2, 3] inside [1, 10], cannot shrink the open interval thanks to Math.max, and main prints [[1, 10]] for that case. Two intervals with the same start always overlap, whichever order the sort leaves them in. And when every interval overlaps the next, as in [1, 2], [2, 3], [3, 4], the open interval keeps growing into the single answer [1, 4].
8Follow-up questions
How do you insert a new interval into a list that is already sorted and merged?
We do not need to sort again, because the list is already in order. We walk it once in three phases. First we copy every interval that ends before the new one starts, since those lie entirely to its left. Then, while the next interval starts at or before the new interval's end, it overlaps, so we widen the new interval to the smaller start and the larger end and move on. Then we add the widened new interval and copy everything that is left. That is one pass, O(n) time.
How many meeting rooms are needed for a list of meetings?
This is a cousin of our problem, but now we need to know how many intervals are open at the same moment, not just which ones join. Sort the start times and the end times separately. Walk through the starts in order with a second index on the ends. Each start that comes before the earliest unfinished end needs one more room, and each end that comes first frees a room. The largest number of rooms in use at any moment is the answer, in O(n log n) time. A min-heap of end times gives the same result.
9Conclusion
We merged overlapping intervals by sorting them by start and sweeping once with a single open interval. An interval that starts at or before the open end stretches it to the larger end, and a gap closes it for good, because nothing later can reach back. The last open interval is added after the loop. That is O(n log n) time and O(n) space. The clue to remember is a list of ranges to merge or compare: sort by start, and the all-pairs question becomes a question about neighbours.
Open with
Let me check the conventions first. I will treat intervals as closed, so [1, 4] and [4, 5] touch and merge, I will not assume the input is sorted, and I will return the merged intervals sorted by start.
Then, if they want more
The brute force repeatedly finds any overlapping pair and merges it, which can reach O(n cubed) because it starts over after every merge. Since these are ranges, I will sort them by start. Then I sweep once, keeping one open interval.
If the next interval starts at or before the open end, they overlap, and I set the end to the max of the two ends; the max matters because a contained interval must not shrink the open one.
If the next interval starts after the open end, there is a gap, and because everything later starts even further right, nothing can overlap the open interval any more, so I add it to the result and open the next one. After the loop I add the last open interval.
Sorting is O(n log n) and the sweep is O(n), so O(n log n) overall, with O(n) space for the result. I sort with Comparator.comparingInt rather than subtracting starts, to avoid overflow. For half-open intervals I would change the test to strictly less than.
About this answer
- Last updated
- 14 November 2026
- Written for
- Java 21, using only java.util
- Checked
- The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
- Where the question comes from
- Public interview write-ups, reworded by Scrivio; counted 23 times in that collection. How it is counted
- Official documentation
- Comparator (Java 21), Arrays (Java 21), ArrayList (Java 21), java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Merge all overlapping intervals in a list of intervals.": https://scrivio-interview-library.netlify.app/data-structures/solutions/merge-all-overlapping-intervals-in-a-list-of-intervals-9ffcb5/