Merge two unsorted intervals
Merge two unsorted intervals is a easy intervals problem solved with the basics pattern.
The best approach, direct formula, runs in O(1) time and O(1) space.
Below are 2 approaches in Java, from order them first up.
Problem
Given two intervals in no particular order, merge them into one if they overlap; otherwise report that they cannot be merged.
Examples
Example 1
- Input
a = [6, 9], b = [2, 7]- Output
[2, 9]
Example 2
- Input
a = [6, 9], b = [1, 3]- Output
no merge (they do not overlap)
Constraints
- Closed intervals; order unknown.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Order them first | O(1) | O(1) |
| Direct formula | O(1) | O(1) |
1Order them first
O(1)O(1)Swap so that a starts first, then apply the sorted rule.
- If b.start < a.start, swap.
- If b.start > a.end, return null.
- Return [a.start, max(a.end, b.end)].
class Solution {
static int[] merge(int[] a, int[] b) {
if (b[0] < a[0]) { int[] t = a; a = b; b = t; }
if (b[0] > a[1]) return null;
return new int[] { a[0], Math.max(a[1], b[1]) };
}
}2Direct formula
O(1)O(1)Overlap test max(starts) <= min(ends); if it passes, the union is [min(starts), max(ends)].
- If max(a0, b0) > min(a1, b1), return null.
- Return [min(a0, b0), max(a1, b1)].
class Solution {
static int[] merge(int[] a, int[] b) {
if (Math.max(a[0], b[0]) > Math.min(a[1], b[1])) return null;
return new int[] { Math.min(a[0], b[0]), Math.max(a[1], b[1]) };
}
}Edge cases to test
- One inside the other
- Touching intervals like [1, 3] and [3, 5]
Hints
Hint 1
If they overlap, the merged interval runs from the smaller start to the larger end.
FAQ
What is the best time complexity for Merge two unsorted intervals?
Direct formula runs in O(1) time and O(1) extra space.
Which pattern does Merge two unsorted intervals use?
It is a intervals problem that uses the basics pattern. Other problems with the same pattern: Detect overlap unsorted, Detect overlap sorted intervals, Interval List Intersections.
Is there a brute force solution for Merge two unsorted intervals?
Yes. Order them first takes O(1) time and O(1) space. Swap so that a starts first, then apply the sorted rule.
Which edge cases should I test for Merge two unsorted intervals?
One inside the other; Touching intervals like [1, 3] and [3, 5].