3 minutes
Leetcode 1272
What This Code Is Doing:
We make a new resulting array and then loop through intervals
.
What we need to know for the following if and else statements is when the code loops through intervals
, we get interval
per iteration. interval
is in the format [start, end]
. Also, the constraints say -10^9 <= start < end <= 10^9
, so we can see that start
and end
are never on the exact same location and the start
is always lesser than end
.
The if and else statments are as follows:
When we do the if statment:
if interval[0] < toBeRemoved[0] && toBeRemoved[1] < interval[1] {
we are checking whether thestart
ofinterval
is smaller than thestart
oftoBeRemoved
and theend
ofinterval
is greater than theend
oftoBeRemoved
, like in the following image: (Note:interval
is green andtoBeRemoved
is red) Thestart
ofinterval
is smaller than thestart
oftoBeRemoved
, and theend
ofinterval
is greater than theend
oftoBeRemoved
.The first else if statment is
else if interval[0] < toBeRemoved[0] && interval[1] > toBeRemoved[0] && interval[1] <= toBeRemoved[1] {
. It is for if the interception ofinterval
andtoBeRemoved
is on the right oftoBeRemoved
, this can be shown with an image: This is for ifinterval
’sstart
is smaller thantoBeRemoved
’sstart
,intervals
’send
is smaller thantoBeRemoved
’send
, andinterval
’send
is greater thantoBeRemoved
’sstart
.The next else if is
else if interval[0] >= toBeRemoved[0] && interval[0] < toBeRemoved[1] && interval[1] > toBeRemoved[1] {
. Is for the same thing as the first else if except it is on the other side oftoBeRemoved
. This can be shown using an image:The next else if is
else if interval[0] >= toBeRemoved[0] && interval[0] < toBeRemoved[1] && interval[1] <= toBeRemoved[1] && interval[1] > toBeRemoved[0] {
. This is for if thestart
ofinterval
is greater than thestart
oftoBeRemoved
and theend
ofinterval
is smaller thanend
oftoBeRemoved
. This can be shown using an image:And last but not least our else. This is for if there is no overlap of
interval
andtoBeRemoved
. This can be shown using an image:
That is all there is to the code, thank you for reading.
The Code:
func removeInterval(intervals [][]int, toBeRemoved []int) [][]int {
res := [][]int{}
for _, interval := range intervals {
if interval[0] < toBeRemoved[0] && toBeRemoved[1] < interval[1] {
res = append(res, []int{interval[0], toBeRemoved[0]},
[]int{toBeRemoved[1], interval[1]})
} else if interval[0] < toBeRemoved[0] && interval[1] > toBeRemoved[0]
&& interval[1] <= toBeRemoved[1] {
res = append(res, []int{interval[0], toBeRemoved[0]})
} else if interval[0] >= toBeRemoved[0] && interval[0] < toBeRemoved[1]
&& interval[1] > toBeRemoved[1] {
res = append(res, []int{toBeRemoved[1], interval[1]})
} else if interval[0] >= toBeRemoved[0] && interval[0] < toBeRemoved[1]
&& interval[1] <= toBeRemoved[1] && interval[1] > toBeRemoved[0] {
continue
} else {
res = append(res, interval)
}
}
return res
}