|
| 1 | +## Overlapping Problem |
| 2 | +Given a collection of Intervals, the task is to merge all of the overlapping Intervals. [🔗Goto](https://practice.geeksforgeeks.org/problems/8a644e94faaa94968d8665ba9e0a80d1ae3e0a2d/1/?page=1&difficulty[]=1&status[]=unsolved&company[]=Microsoft&category[]=Arrays&category[]=Strings&sortBy=accuracy#) |
| 3 | + |
| 4 | +<details> |
| 5 | +<summary>Full Code</summary> |
| 6 | + |
| 7 | +```java |
| 8 | +import java.util.*; |
| 9 | +import java.lang.*; |
| 10 | +import java.io.*; |
| 11 | +class GFG |
| 12 | +{ |
| 13 | + public static void main(String[] args) throws IOException |
| 14 | + { |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + int T = Integer.parseInt(br.readLine().trim()); |
| 17 | + while(T-->0) |
| 18 | + { |
| 19 | + int n = Integer.parseInt(br.readLine().trim()); |
| 20 | + String[] s = br.readLine().trim().split(" "); |
| 21 | + int[][] Intervals = new int[n][2]; |
| 22 | + int j = 0; |
| 23 | + for(int i = 0; i < n; i++){ |
| 24 | + Intervals[i][0] = Integer.parseInt(s[j]); |
| 25 | + j++; |
| 26 | + Intervals[i][1] = Integer.parseInt(s[j]); |
| 27 | + j++; |
| 28 | + } |
| 29 | + Solution obj = new Solution(); |
| 30 | + int[][] ans = obj.overlappedInterval(Intervals); |
| 31 | + for(int i = 0; i < ans.length; i++){ |
| 32 | + for(j = 0; j < ans[i].length; j++){ |
| 33 | + System.out.print(ans[i][j] + " "); |
| 34 | + } |
| 35 | + } |
| 36 | + System.out.println(); |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | +``` |
| 41 | +</details> |
| 42 | + |
| 43 | +```java |
| 44 | +class Solution |
| 45 | +{ |
| 46 | + public int[][] overlappedInterval(int[][] Intervals) |
| 47 | + { |
| 48 | + //sort according the first element |
| 49 | + Arrays.sort(Intervals, new Comparator<int []>(){ |
| 50 | + public int compare(int []arr1,int []arr2){ |
| 51 | + return arr1[0] - arr2[0]; |
| 52 | + } |
| 53 | + }); |
| 54 | + |
| 55 | + Stack<int[]> st = new Stack<>(); |
| 56 | + //Iterate for each eleemnt and push into stack |
| 57 | + |
| 58 | + for(int[] arr:Intervals){ |
| 59 | + //if stack is empty then push first element |
| 60 | + if(st.empty()){ |
| 61 | + st.push(arr); |
| 62 | + } |
| 63 | + else{ |
| 64 | + int [] temp = st.peek(); |
| 65 | + |
| 66 | + //for a different range add the new range |
| 67 | + if(temp[1]<arr[0]){ |
| 68 | + st.push(arr); |
| 69 | + } |
| 70 | + |
| 71 | + // If range overlapps then modify the 2nd element |
| 72 | + else if(temp[1]>=arr[0] && temp[1] < arr[1]){ |
| 73 | + int []popped = st.pop(); |
| 74 | + popped[1] = arr[1]; |
| 75 | + st.push(popped); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + int ans[][]=new int[st.size()][2]; |
| 80 | + int i = 0; |
| 81 | + |
| 82 | + // Convert Stack Element into Array |
| 83 | + for(int[]arr : st){ |
| 84 | + ans[i] = arr; |
| 85 | + i++; |
| 86 | + } |
| 87 | + return ans; |
| 88 | + } |
| 89 | +} |
| 90 | +``` |
0 commit comments