LeetCode 56: Merge Intervals Solution
Master LeetCode problem 56 (Merge Intervals), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To merge overlapping intervals, we first sort the intervals based on their start times. Then, we iterate through the sorted intervals and merge overlapping intervals by comparing the end time of the current interval with the start time of the next interval. If they overlap, we update the end time to be the maximum of the two end times. If they do not overlap, we add the current interval to the result and continue with the next interval.
Time Complexity: O(n log n) - Sorting the intervals Space Complexity: O(n) - Space required for the result
Solution Code
class Solution {
public int[][] merge(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
for (int[] interval : intervals) {
if (merged.isEmpty() || merged.get(merged.size() - 1)[1] < interval[0]) {
merged.add(interval);
} else {
merged.get(merged.size() - 1)[1] = Math.max(merged.get(merged.size() - 1)[1], interval[1]);
}
}
return merged.toArray(new int[merged.size()][]);
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 56 (Merge Intervals)?
This page provides optimized solutions for LeetCode problem 56 (Merge Intervals) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 56 (Merge Intervals)?
The time complexity for LeetCode 56 (Merge Intervals) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 56 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 56 in Java, C++, or Python.