Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.
Note that you don't need to modify intervals in-place. You can make a new array and return it.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
Example 2:
Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
Constraints:
0 <= intervals.length <= 104intervals[i].length == 20 <= starti <= endi <= 105intervals is sorted by starti in ascending order.newInterval.length == 20 <= start <= end <= 105Problem summary: You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval. Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary). Return intervals after the insertion. Note that you don't need to modify intervals in-place. You can make a new array and return it.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[1,3],[6,9]] [2,5]
[[1,2],[3,5],[6,7],[8,10],[12,16]] [4,8]
merge-intervals)range-module)count-integers-in-intervals)import java.util.*;
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> ans = new ArrayList<>();
int i = 0, n = intervals.length;
// 1) Add intervals that end before newInterval starts.
while (i < n && intervals[i][1] < newInterval[0]) {
ans.add(intervals[i++]);
}
// 2) Merge all intervals that overlap newInterval.
int start = newInterval[0], end = newInterval[1];
while (i < n && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
ans.add(new int[] { start, end });
// 3) Add the rest.
while (i < n) {
ans.add(intervals[i++]);
}
return ans.toArray(new int[ans.size()][]);
}
}
func insert(intervals [][]int, newInterval []int) [][]int {
ans := [][]int{}
i, n := 0, len(intervals)
for i < n && intervals[i][1] < newInterval[0] {
ans = append(ans, intervals[i])
i++
}
start, end := newInterval[0], newInterval[1]
for i < n && intervals[i][0] <= end {
if intervals[i][0] < start {
start = intervals[i][0]
}
if intervals[i][1] > end {
end = intervals[i][1]
}
i++
}
ans = append(ans, []int{start, end})
for i < n {
ans = append(ans, intervals[i])
i++
}
return ans
}
class Solution:
def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
ans: List[List[int]] = []
i, n = 0, len(intervals)
while i < n and intervals[i][1] < newInterval[0]:
ans.append(intervals[i])
i += 1
start, end = newInterval
while i < n and intervals[i][0] <= end:
start = min(start, intervals[i][0])
end = max(end, intervals[i][1])
i += 1
ans.append([start, end])
while i < n:
ans.append(intervals[i])
i += 1
return ans
impl Solution {
pub fn insert(intervals: Vec<Vec<i32>>, new_interval: Vec<i32>) -> Vec<Vec<i32>> {
let mut ans: Vec<Vec<i32>> = Vec::new();
let mut i = 0usize;
let n = intervals.len();
let mut cur = new_interval;
while i < n && intervals[i][1] < cur[0] {
ans.push(intervals[i].clone());
i += 1;
}
while i < n && intervals[i][0] <= cur[1] {
cur[0] = cur[0].min(intervals[i][0]);
cur[1] = cur[1].max(intervals[i][1]);
i += 1;
}
ans.push(cur);
while i < n {
ans.push(intervals[i].clone());
i += 1;
}
ans
}
}
function insert(intervals: number[][], newInterval: number[]): number[][] {
const ans: number[][] = [];
let i = 0;
const n = intervals.length;
while (i < n && intervals[i][1] < newInterval[0]) {
ans.push(intervals[i]);
i++;
}
let [start, end] = newInterval;
while (i < n && intervals[i][0] <= end) {
start = Math.min(start, intervals[i][0]);
end = Math.max(end, intervals[i][1]);
i++;
}
ans.push([start, end]);
while (i < n) {
ans.push(intervals[i]);
i++;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.