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 thestartofintervalis smaller than thestartoftoBeRemovedand theendofintervalis greater than theendoftoBeRemoved, like in the following image:
(Note: intervalis green andtoBeRemovedis red) Thestartofintervalis smaller than thestartoftoBeRemoved, and theendofintervalis greater than theendoftoBeRemoved.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 ofintervalandtoBeRemovedis on the right oftoBeRemoved, this can be shown with an image:
This is for if interval’sstartis smaller thantoBeRemoved’sstart,intervals’sendis smaller thantoBeRemoved’send, andinterval’sendis 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 thestartofintervalis greater than thestartoftoBeRemovedand theendofintervalis smaller thanendoftoBeRemoved. This can be shown using an image:
And last but not least our else. This is for if there is no overlap of
intervalandtoBeRemoved. 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
}