57. Insert Interval
Tags:
Medium
Skills:
Interval
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Bài toán yêu cầu insert một interval mới vào một danh sách các interval đã được sắp xếp và không giao nhau, sau đó trả về danh sách interval mới vẫn được sắp xếp và không giao nhau (nêu overlap thì phải merge lại)
Approach
Solution
1function insert(intervals: number[][], newInterval: number[]): number[][] {
2 let [start, end] = newInterval;
3 let inserted = false;
4 const res: number[][] = [];
5 for (const [curr_start, curr_end] of intervals) {
6 // newInterval lays before current interval
7 if (end < curr_start) {
8 if (!inserted) {
9 res.push([start, end]);
10 inserted = true
11 }
12
13 res.push([curr_start, curr_end])
14 } else if (curr_end < start) {
15 // newInterval lays after current interval
16 res.push([curr_start, curr_end])
17 } else {
18 // overlap
19 start = Math.min(curr_start, start);
20 end = Math.max(curr_end, end);
21 }
22 }
23
24 if (!inserted) {
25 res.push([start, end])
26 }
27
28 return res;
29};