Skip to content

Commit

Permalink
Create Insert interval
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Dec 9, 2024
1 parent 08dda70 commit 684161e
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions Insert interval
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//Insert interval

import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;

class GFG {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();

while(T-- > 0) {
int n = sc.nextInt();
int a[][] = new int[n][2];

for(int i = 0; i < n; i++) {
a[i][0] = sc.nextInt();
a[i][1] = sc.nextInt();
}

int h[] = new int[2];
h[0] = sc.nextInt();
h[1] = sc.nextInt();
Solution obj = new Solution();
ArrayList<int[]> ans = obj.insertInterval(a, h);

System.out.print("[");
for(int i = 0; i < ans.size(); i++) {
System.out.print("[");
System.out.print(ans.get(i)[0] + "," + ans.get(i)[1]);
System.out.print("]");
if (i != ans.size() - 1) System.out.print(",");
}
System.out.println("]");
System.out.println("~");
}
}
}

class Solution {
static ArrayList<int[]> insertInterval(int[][] intervals, int[] newInterval) {
ArrayList<int[]> res = new ArrayList<>();
int i = 0;
int n = intervals.length;

while(i < n && intervals[i][1] < newInterval[0]) {
res.add(intervals[i]);
i++;
}

while(i < n && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(newInterval[0], intervals[i][0]);
newInterval[1] = Math.max(newInterval[1], intervals[i][1]);
i++;
}

res.add(newInterval);

while(i < n) {
res.add(intervals[i]);
i++;
}

return res;
}
}

0 comments on commit 684161e

Please sign in to comment.