Skip to content

Commit

Permalink
Create Overlapping intervals
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored Dec 8, 2024
1 parent 6428f3a commit 08dda70
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Overlapping intervals
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//Overlapping intervals

import java.io.*;
import java.util.*;

class GFG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());

while(T-- > 0) {
int n = Integer.parseInt(br.readLine().trim());
int[][] arr = new int[n][2];

for(int i = 0; i < n; i++) {
String temp[] = br.readLine().trim().split(" ");
arr[i][0] = Integer.parseInt(temp[0]);
String x = temp[1];
arr[i][1] = Integer.parseInt(x);
}

Solution obj = new Solution();
List<int[]> ans = obj.mergeOverlap(arr);

for(int[] interval : ans) {
System.out.print(interval[0] + " " + interval[1] + " ");
}
System.out.println();
}
}
}

class Solution {
public List<int[]> mergeOverlap(int[][] arr) {
Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> res = new ArrayList<>();
res.add(new int[]{arr[0][0], arr[0][1]});

for(int i = 1; i < arr.length; i++) {
int[] last = res.get(res.size() - 1);
int[] curr = arr[i];

if(curr[0] <= last[1]) {
last[1] = Math.max(last[1], curr[1]);
}
else {
res.add(new int[]{curr[0], curr[1]});
}
}

return res;
}
}

0 comments on commit 08dda70

Please sign in to comment.