Skip to content

Commit 93ab03a

Browse files
authored
Update Remove Interval.java
1 parent 44b4003 commit 93ab03a

File tree

1 file changed

+33
-14
lines changed

1 file changed

+33
-14
lines changed

Medium/Remove Interval.java

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,37 @@
11
class Solution {
2-
public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) {
3-
List<List<Integer>> result = new ArrayList<>();
4-
for (int[] interval : intervals) {
5-
if (interval[0] > toBeRemoved[1] || interval[1] < toBeRemoved[0]) {
6-
result.add(Arrays.asList(interval[0], interval[1]));
7-
} else {
8-
if (interval[0] < toBeRemoved[0]) {
9-
result.add(Arrays.asList(interval[0], toBeRemoved[0]));
2+
public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) {
3+
List<List<Integer>> result = new ArrayList<>();
4+
int n = intervals.length;
5+
int removeStart = toBeRemoved[0];
6+
int removeEnd = toBeRemoved[1];
7+
for (int i = 0; i < n; i++) {
8+
int currStart = intervals[i][0];
9+
int currEnd = intervals[i][1];
10+
// complete overlap hence skipping complete interval
11+
if (currStart >= removeStart && currEnd <= removeEnd) {
12+
continue;
13+
}
14+
// no overlap hence adding complete interval
15+
if ((currStart <= removeStart && currEnd <= removeStart) || (currStart >= removeEnd && currEnd >= removeEnd)) {
16+
result.add(List.of(currStart, currEnd));
17+
continue;
18+
}
19+
// partial overlaps
20+
if (currStart <= removeStart) {
21+
int newStart = Math.min(currStart, removeStart);
22+
int newEnd = Math.max(currStart, removeStart);
23+
if (newStart != newEnd) {
24+
result.add(List.of(newStart, newEnd));
25+
}
26+
}
27+
if (currEnd >= removeEnd) {
28+
int newStart = Math.min(currEnd, removeEnd);
29+
int newEnd = Math.max(currEnd, removeEnd);
30+
if (newStart != newEnd) {
31+
result.add(List.of(newStart, newEnd));
32+
}
33+
}
1034
}
11-
if (interval[1] > toBeRemoved[1]) {
12-
result.add(Arrays.asList(toBeRemoved[1], interval[1]));
13-
}
14-
}
35+
return result;
1536
}
16-
return result;
17-
}
1837
}

0 commit comments

Comments
 (0)