InterviewPrep

Leetcode 56 Merge Intervals (Java)

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

Solution:

We can solve this by comparing the start of the next interval with the end of the current interval and merged if the start of the next interval is less than the end of the current interval.
For this we need to sort the interval based on the start of the intervals.

Note: Please try to solve it yourself before looking into the solution below

class Solution {
    public int[][] merge(int[][] intervals) {
        
        if(intervals.length<=1) return intervals;
        
        List<int[]> mergedIntervals = new ArrayList<>();
        
        Arrays.sort(intervals, (arr1, arr2) -> Integer.compare(arr1[0], arr2[0]));
        
        int[] currentInterval = intervals[0];
        
        mergedIntervals.add(currentInterval);
        
        for(int[] interval: intervals){
            int currentStart = currentInterval[0];
            int currentEnd = currentInterval[1];
            int newStart = interval[0];
            int newEnd = interval[1];
            
            if(currentEnd>=newStart){
                currentInterval[1] = Math.max(currentEnd, newEnd);
            }else{
                currentInterval = interval;
                mergedIntervals.add(currentInterval);
            }
            
        }
        
        
        return mergedIntervals.toArray(new int[mergedIntervals.size()][]);
    }
}
rajendra

Recent Posts

Largest Unique Number Java Solution

Question : Given an array of integers A, return the largest integer that only occurs once.…

9 months ago

Jump Search Algorithm In Java

Jump search algorithm is a pretty new algorithm to search for an element in a…

1 year ago

Knuth Morris Pratt Pattern Search Algorithm

What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…

1 year ago

Binary Search Algorithm In Java

Binary Search is a Logarithmic search which finds the target element in a sorted array…

1 year ago

Leetcode Integer to Roman Java Solution

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…

2 years ago

Leetcode Container With Most Water Java Solution

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…

2 years ago

This website uses cookies.