← Back to DSA
#57
Insert Interval
Insert Interval solution for LeetCode 57, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Insert Interval
Why it belongs on this sheet
This is the natural follow-up after merge intervals and checks if you can reason through cases without losing order.
Pattern
Three interval zones
Approach
Add all intervals that end before the new one starts. Then merge all intervals that overlap the new interval. Finally append the remaining intervals.
Java solution
import java.util.ArrayList;
import java.util.List;
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> answer = new ArrayList<>();
int i = 0;
while (i < intervals.length && intervals[i][1] < newInterval[0]) {
answer.add(intervals[i++]);
}
while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}
answer.add(newInterval);
while (i < intervals.length) {
answer.add(intervals[i++]);
}
return answer.toArray(new int[answer.size()][]);
}
}
Complexity
- Time:
O(n) - Space:
O(n)for the output
Interview note
The three-phase structure is the cleanest way to explain this problem under pressure.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)