Skip to content

Commit f3317f5

Browse files
committed
Added solution for Leetcode 0056. Merge Intervals
1 parent 32c7798 commit f3317f5

File tree

3 files changed

+56
-3
lines changed

3 files changed

+56
-3
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
### 1. Sorting Approach
2+
Sort Intervals:
3+
* Sort the intervals based on their start times using a comparator.
4+
Initialize:
5+
* Create a list to store the merged intervals.
6+
* Start with the first interval as the current interval to merge.
7+
8+
Loop through Sorted Intervals:
9+
* For each interval, check if it overlaps with the current interval:
10+
* If it overlaps, merge them by updating the end of the current interval to the maximum end of both intervals.
11+
* If it doesn't overlap, add the current interval to the list of merged intervals and update the current interval to the next interval.
12+
Add Last Interval:
13+
* After the loop, add the last current interval to the list of merged intervals.
14+
Return Result:
15+
* Convert the list of merged intervals to an array and return it.
16+
17+
Time Complexity: O(n log n)
18+
Space Complexity: O(n)
19+
20+
### 2. Optimized Sorting Approach Using LinkedList
21+
Sort Intervals:
22+
* Sort the intervals based on their start times using a comparator.
23+
24+
Initialize:
25+
* Create a LinkedList to store the merged intervals.
26+
27+
Loop through Sorted Intervals:
28+
* For each interval, check if it overlaps with the last interval in the LinkedList:
29+
* If it overlaps, merge them by updating the end of the last interval in the LinkedList to the maximum end of both intervals.
30+
* If it doesn't overlap, add the interval to the LinkedList.
31+
Return Result:
32+
* Convert the LinkedList of merged intervals to an array and return it.
33+
Time Complexity: O(n log n)
34+
Space Complexity: O(n)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import java.util.Arrays;
2+
import java.util.LinkedList;
3+
4+
public class Solution {
5+
public static void main(String[] args) {
6+
int[][] intervals = {{1,3},{2,6},{8,10},{15,18}};
7+
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
8+
9+
LinkedList<int[]> mergedIntervals = new LinkedList<int[]>();
10+
11+
for(int[]interval : intervals) {
12+
if(mergedIntervals.isEmpty() || mergedIntervals.getLast()[1] < interval[0]){
13+
mergedIntervals.add(interval);
14+
}else{
15+
mergedIntervals.getLast()[1] = Math.max(mergedIntervals.getLast()[1], interval[1]);
16+
}
17+
}
18+
19+
int[][] arrayMergedIntervals = mergedIntervals.toArray(new int[mergedIntervals.size()][]);
20+
System.out.println(Arrays.deepToString(arrayMergedIntervals));
21+
}
22+
}

problems/01. Arrays/Part 02/02. Leetcode Medium 0056. Merge Intervals/java/Solution.java

Lines changed: 0 additions & 3 deletions
This file was deleted.

0 commit comments

Comments
 (0)