Skip to content

Commit 39ec1b7

Browse files
Merge pull request #230 from aneeshgupta25/main
Adding solution for Merge Intervals (Leetcode 56)
2 parents 01abdeb + dbfc2a6 commit 39ec1b7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Java/Stack/Merge_Intervals.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*Problem
2+
56. Merge Intervals (LEETCODE)
3+
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping
4+
intervals that cover all the intervals in the input.
5+
6+
Meaning -> For example, if we have 2 meetings, one is scheduled from 7am-8am and the other one is from 7:30am-9am. Then we can merge these
7+
2 meetings 2 get 1 -> (7am-9am).
8+
9+
How to implement -> We'll be using Stack data structure to solve this problem.
10+
11+
IDEOLOGY -> Sort the given elements of the array. Then merge 2 meetings if start time of the second meeting is encountered before the end time of the first meeting. */
12+
13+
14+
class Solution {
15+
public int[][] merge(int[][] intervals) {
16+
Arrays.sort(intervals, (a,b)-> Integer.compare(a[0], b[0])); //This sorting will sort the meetings according to their start time.
17+
18+
Stack<int[]> st = new Stack<>();
19+
st.push(intervals[0]); //Initially, we'll push the first meeting element into the stack.
20+
21+
for(int i = 1; i < intervals.length; i++){
22+
if(st.peek()[1] >= intervals[i][0]){
23+
int[] arr = st.pop();
24+
arr[1] = Math.max(arr[1], intervals[i][1]);
25+
st.push(arr);
26+
} else {
27+
st.push(intervals[i]);
28+
}
29+
}
30+
int[][] ans = new int[st.size()][2];
31+
int index = ans.length-1;
32+
while(index >= 0){
33+
ans[index] = st.pop();
34+
index--;
35+
}
36+
return ans;
37+
}
38+
}

0 commit comments

Comments
 (0)