LeetCode 1272: Remove Interval

Array

Problem Description

Explanation:

Given a list of intervals and a target interval to remove, we need to remove the overlapping portions of the intervals with the target interval.

  1. Iterate through each interval in the list.
  2. If the current interval does not overlap with the target interval, add it to the result.
  3. If the current interval overlaps with the target interval:
    • If the current interval is completely inside the target interval, skip it.
    • If the current interval overlaps on the left side of the target interval, add the non-overlapping portion on the left side to the result.
    • If the current interval overlaps on the right side of the target interval, add the non-overlapping portion on the right side to the result.
    • If the current interval completely covers the target interval, skip it. :

Solutions

class Solution {
    public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) {
        List<List<Integer>> result = new ArrayList<>();
        
        for (int[] interval : intervals) {
            if (interval[0] >= toBeRemoved[1] || interval[1] <= toBeRemoved[0]) {
                result.add(Arrays.asList(interval[0], interval[1]));
            } else {
                if (interval[0] < toBeRemoved[0]) {
                    result.add(Arrays.asList(interval[0], toBeRemoved[0]));
                }
                if (interval[1] > toBeRemoved[1]) {
                    result.add(Arrays.asList(toBeRemoved[1], interval[1]));
                }
            }
        }
        
        return result;
    }
}

Loading editor...