Tutorialspoint
Problem
Solution
Submissions

Merge Intervals

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to merge all overlapping intervals from an array of intervals and return an array of the non-overlapping intervals that cover all the intervals in the input. Each interval is represented as a pair of integers [start, end].

Example 1
  • Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
  • Output: [[1,6],[8,10],[15,18]]
  • Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2
  • Input: intervals = [[1,4],[4,5]]
  • Output: [[1,5]]
  • Explanation: Intervals [1,4] and [4,5] are considered overlapping since they share the endpoint 4.
Constraints
  • 1 ≤ intervals.length ≤ 10^4
  • intervals[i].length == 2
  • 0 ≤ start_iend_i ≤ 10^4
  • Time Complexity: O(n log n) due to sorting
  • Space Complexity: O(n) for the result
ArraysCapgeminiTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Sort the intervals based on the start times
  • Initialize a result list with the first interval
  • Iterate through the remaining intervals
  • If the current interval overlaps with the last interval in the result, merge them
  • Otherwise, add the current interval to the result list

Steps to solve by this approach:

 Step 1: Sort the intervals array based on the start time of each interval.
 Step 2: Create a result list to store merged intervals.
 Step 3: Add the first interval to the result list and set it as the current interval.
 Step 4: Iterate through each interval in the sorted array.
 Step 5: If the current interval overlaps with the last merged interval in result, update the end time of the last interval to be the maximum of both end times.
 Step 6: If there's no overlap, add the current interval to the result list.
 Step 7: Convert the result list to an array and return it.

Submitted Code :