public class InsertInterval
{
public InsertInterval(){}
public int[][] insert(int[][] intervals, int[] newInterval)
{
List<int[]> result= new ArrayList<>();
if(newInterval.length == 0)
{return intervals;}
if(intervals.length == 0)
{
result.add(newInterval);
return result.toArray(new int[result.size()][2]);
}
if(intervals.length == 1)
{
if(intervals[0][1] < newInterval[0])
{
result.add(intervals[0]);
result.add(newInterval);
return result.toArray(new int[result.size()][2]);
}
else if(intervals[0][0] > newInterval[1])
{
result.add(newInterval);
result.add(intervals[0]);
return result.toArray(new int[result.size()][2]);
}
else
{
int[] temp= new int[2];
temp[1]= intervals[0][1] >= newInterval[1] ?
intervals[0][1] : newInterval[1];
temp[0]= intervals[0][0] <= newInterval[0] ?
intervals[0][0] : newInterval[0];
result.add(temp);
return result.toArray(new int[result.size()][2]);
}
}
int pause= newInterval[0];
int index= intervals.length-1;
for(int i=0;i<intervals.length-1;i++)
{
if(intervals[i][0] <= pause &&
pause <= intervals[i+1][0])
{
index=i;
break;
}
}
if(newInterval[0] <= intervals[0][0])
{index= 0;}
for(int i=0;i<index;i++)
{
result.add(intervals[i]);
}
int start= newInterval[0];
int end= newInterval[1];
int[] arr= intervals[index];
if(start > arr[1])
{
result.add(intervals[index]);
}
else if(end < arr[0])
{
result.add(new int[]{start, end});
start= arr[0];
end= arr[1];
}
else
{
start= start <= arr[0] ? start : arr[0];
end= end >= arr[1] ? end : arr[1];
}
for(int i=index+1;i<intervals.length;i++)
{
int[] ans= intervals[i];
if(start <= ans[0] && end >= ans[1])
{continue;}
else
{
if(end < ans[0])
{
result.add(new int[]{start, end});
start= ans[0];
end= ans[1];
}
else
{end= Math.max(end, ans[1]);}
}
}
result.add(new int[]{start, end});
return result.toArray(new int[result.size()][2]);
}
}