Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Given int[][] intervals such as [[1,3],[2,6],[8,10],[9,12],[15,18]], write a Java method that merges all overlapping intervals. Explain the complexity and how you treat touching intervals like [1,4] and [4,5].

We sort the intervals by start with Arrays.sort(intervals, Comparator.comparingInt(a -> a[0])), which costs O(n log n), and then walk them once: if the next interval starts at or before the current end we extend the end with Math.max, otherwise we emit the current interval and start a new one. The walk is O(n), so the whole method is O(n log n). Whether touching intervals such as [1,4] and [4,5] merge is a requirement question: a <= comparison merges them, a < comparison keeps them apart.

Why this question is asked

Merging intervals comes up constantly in real systems: combining a person's busy slots in a calendar, compacting time ranges of log data, merging IP ranges in a firewall rule set, or joining reserved seat ranges. Interviewers like it because it rewards one idea, sorting first, and then tests the details: the comparator, the overlap condition, nested intervals and the output type. In this answer, we will recap what overlap means, see why sorting makes the problem easy, write the method, look at the touching-intervals decision and at a comparator bug that hides in many solutions, and answer the follow-up about inserting one interval.

1A Quick Recap of Overlapping Intervals

An interval [start, end] stands for all points from start to end. Two intervals overlap when one starts before the other ends. [1,3] and [2,6] overlap because 2 is inside [1,3], and together they cover [1,6]. [8,10] and [9,12] become [8,12]. [15,18] overlaps nothing. So the answer for the example is [[1,6],[8,12],[15,18]].

Without sorting, any interval could overlap any other, so we would compare every pair, O(n^2), and merging could cascade: merging two intervals can make the result overlap a third one we already checked. Sorting removes both problems.

2Why Sorting by Start Makes It Easy

Once the intervals are sorted by start, an interval can only overlap the group we are currently building, never an earlier group. The reason is that every earlier group ended before the current group's first interval started, and the next interval starts even later. So one left-to-right pass with a single current interval is enough.

Java
static int[][] merge(int[][] intervals) {
if (intervals.length == 0) return new int[0][];
int[][] sorted = intervals.clone(); // do not reorder the caller's array
Arrays.sort(sorted, Comparator.comparingInt(a -> a[0])); // O(n log n)
List<int[]> out = new ArrayList<>();
int[] current = sorted[0].clone();
for (int i = 1; i < sorted.length; i++) {
int[] next = sorted[i];
if (next[0] <= current[1]) { // overlaps or touches
current[1] = Math.max(current[1], next[1]); // extend, never shrink
} else {
out.add(current); // gap: close this group
current = next.clone();
}
}
out.add(current); // the last group
return out.toArray(new int[0][]);
}
merge(new int[][] {{1,3},{2,6},{8,10},{9,12},{15,18}}); // [[1,6],[8,12],[15,18]]
merge(new int[][] {{1,10},{2,3}}); // [[1,10]] nested
merge(new int[][] {{1,4},{4,5}}); // [[1,5]] touching, with <=
Walking the sorted example
nextcurrent beforeactioncurrent after
[2,6][1,3]2 <= 3: extend end to max(3, 6)[1,6]
[8,10][1,6]8 > 6: emit [1,6][8,10]
[9,12][8,10]9 <= 10: extend end to 12[8,12]
[15,18][8,12]15 > 12: emit [8,12][15,18]
(end)[15,18]emit the last group-
Output: [1,6], [8,12], [15,18].

Notice the Math.max. When an interval is nested inside the current one, like [2,3] inside [1,10], simply setting the end to 3 would shrink the merged interval and lose [3,10]. Taking the maximum keeps the larger end.

We clone the arrays because sort and the end update would otherwise change the caller's data, which is a surprising side effect for a method called merge. We collect into a List<int[]> because we do not know the output size in advance, then convert with toArray(new int[0][]). The sort dominates, so the time is O(n log n); the walk is O(n), and the output takes O(n) space.

3Touching Intervals Are a Requirement Question

With <=, [1,4] and [4,5] merge into [1,5]; with <, they stay as two intervals. Neither is wrong in general. It depends on what the numbers mean. For closed ranges of integers, such as seat numbers 1 to 4 and 4 to 5, they share seat 4, so they overlap. For half-open time ranges, such as meetings from 10:00 to 11:00 and 11:00 to 12:00, they do not overlap at all, but a person viewing a busy calendar may still want them shown as one block. So in the interview, we ask, choose, and say which comparison implements the choice.

4A Comparator Bug That Hides in Many Solutions

Many solutions sort with (a, b) -> a[0] - b[0]. It works on small test inputs and fails on large ones.

Java
int[][] data = {{2_000_000_000, 2_000_000_001}, {-2_000_000_000, 0}};
Arrays.sort(data, (a, b) -> a[0] - b[0]);
// 2_000_000_000 - (-2_000_000_000) overflows to -294,967,296,
// so the comparator says the first interval is smaller: wrong order
Arrays.sort(data, Comparator.comparingInt(a -> a[0])); // correct
Arrays.sort(data, (a, b) -> Integer.compare(a[0], b[0])); // also correct

Subtraction overflows whenever the two values are far apart, and the sign of the result flips. A comparator that gives inconsistent answers can produce a wrongly sorted array, and TimSort may even throw IllegalArgumentException with the message that the comparison method violates its general contract. Comparator.comparingInt and Integer.compare compare without subtracting, so they are always safe.

5Follow-up questions

How would you insert one new interval into an already merged list in O(n)?

Because the list is already sorted and non-overlapping, I do not need to sort again. I walk it in three phases: copy every interval that ends before the new one starts; then, while intervals start at or before the new interval's end, merge them into it by taking the minimum start and the maximum end; then add the merged interval and copy the rest. Each interval is looked at once, so it is O(n), and the output is still sorted and non-overlapping.

What if the input is a stream that is too large to sort in memory?

If it arrives sorted by start, for example from a database query with ORDER BY start, the same single pass works with constant memory, because we only keep the current interval. If it is unsorted and too large, we sort it externally, in chunks written to disk and merged, or let the database do the sort, and then run the pass.

Would you use a record instead of int[]?

In production code, yes: record Interval(int start, int end) with a compact constructor that checks start <= end is clearer and cannot be confused with other int pairs. In the interview I keep int[][] because the question's signature uses it, and I mention the record as the version I would commit.

6Conclusion

In this answer, we saw that sorting by start turns interval merging into a single pass, because after sorting an interval can only overlap the group we are building. We extend the end with Math.max so nested intervals do not shrink the result, emit a group when there is a gap, and collect into a List<int[]> before converting with toArray. The whole method is O(n log n) because of the sort. Whether touching intervals merge depends on what the ranges mean, and comparators must use comparingInt or Integer.compare, never subtraction, which overflows.

What to say in the interviewAbout 100 seconds aloud

Open with

I would sort the intervals by their start using Comparator.comparingInt on the first element, and then walk them once while keeping a current interval. If the next interval starts at or before the current end, they overlap, so I extend the current end to the maximum of the two ends.

Then, if they want more

The maximum matters for nested intervals, like 2 to 3 inside 1 to 10, where just taking the new end would shrink the result.

If the next one starts after the current end, there is a gap, so I add the current interval to the output list and start a new one, and at the end I add the last one. For the example that gives 1 to 6, 8 to 12 and 15 to 18.

The sort is O(n log n) and the walk is O(n), so the total is O(n log n), with O(n) for the output. Sorting is what makes one pass enough: after it, an interval can only overlap the group I am building, never an earlier group.

For touching intervals like 1 to 4 and 4 to 5, I would ask what the numbers mean. For closed integer ranges they share a point and merge, which is the less-or-equal check. For half-open time ranges they do not overlap, which is the strict less-than check.

I also avoid writing the comparator as a subtraction, because that overflows for values far apart and can break the sort.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Given int[][] intervals such as [[1,3],[2,6],[8,10],[9,12],[15,18]], write a Java method...": https://scrivio-interview-library.netlify.app/java/coding-problems/b4deae1cf6/