| 1 | class Solution { |
| 2 | public int[][] insert(int[][] intervals, int[] newInterval) { |
| 3 | List<int[]> list = new ArrayList(); |
| 4 | //We will store the answers in a List of Interval (Arrays of size 2) |
| 5 | |
| 6 | for (int[] in : intervals) { |
| 7 | // iterating over the intervals using enhanced for loop |
| 8 | |
| 9 | if (in[1] < newInterval[0]) { |
| 10 | /* if the end of current interval is less than the start of the new interval to be inserted, we simply add the current interval to our result*/ |
| 11 | list.add(in); |
| 12 | } |
| 13 | |
| 14 | else if (newInterval[1] < in[0]) { |
| 15 | if (in[1] < newInterval[0]) { |
| 16 | /* if the end of new interval to be inserted is less than the start of the current interval , we simply add the new interval to our result and change our element to be added to the current element */ |
| 17 | |
| 18 | list.add(newInterval); |
| 19 | newInterval = in; |
| 20 | } |
| 21 | |
| 22 | else { |
| 23 | /* In this case we have overlapping intervals and we need to merge the intervals, for this we select the starting point as the minimum of new interval and the current interval, and the end point as the maximum of new interval and the current interval */ |
| 24 | |
| 25 | newInterval[0] = Math.min(newInterval[0], in[0]); |
| 26 | newInterval[1] = Math.max(newInterval[1], in[1]); |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | /* we need to add the last interval explicitly as it isn't included in the answer */ |
| 31 | |
| 32 | list.add(newInterval); |
| 33 | |
| 34 | // we use inbuilt method toArray of List Class to change the list to Array |
| 35 | return list.toArray(new int[list.size()][]); |
| 36 | } |
| 37 | } |
nothing calls this directly
no outgoing calls
no test coverage detected