Tutorialspoint
Problem
Solution
Submissions

Merge Intervals

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

Write a JavaScript program to merge overlapping intervals. Given an array of intervals where each interval is represented as [start, end], merge all overlapping intervals and return an array of non-overlapping intervals that cover all the intervals in the input. Two intervals overlap if they have at least one common point.

Example 1
  • Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
  • Output: [[1,6],[8,10],[15,18]]
  • Explanation:
    • Sort intervals by start time: [[1,3],[2,6],[8,10],[15,18]].
    • Compare [1,3] and [2,6]: 3 >= 2, so they overlap.
    • Merge [1,3] and [2,6] to get [1,6]. Compare [1,6] and [8,10]: 6 < 8, so no overlap.
    • Compare [8,10] and [15,18]: 10 < 15, so no overlap.
    • Final result: [[1,6],[8,10],[15,18]]
Example 2
  • Input: intervals = [[1,4],[4,5]]
  • Output: [[1,5]]
  • Explanation:
    • Sort intervals by start time: [[1,4],[4,5]].
    • Compare [1,4] and [4,5]: 4 >= 4, so they overlap (touching intervals).
    • Merge [1,4] and [4,5] to get [1,5]. Final result: [[1,5]]
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 array
ArraysDeloitteSwiggy
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 by their start times to process them in order
  • Initialize result array with the first interval
  • Iterate through remaining intervals and compare with the last interval in result
  • If current interval overlaps with last interval in result, merge them
  • If no overlap, add current interval to result
  • Two intervals [a,b] and [c,d] overlap if b >= c (assuming a <= c after sorting)

Steps to solve by this approach:

 Step 1: Handle edge case where intervals array has 0 or 1 element

 Step 2: Sort the intervals array by start time using custom comparator
 Step 3: Initialize result array with the first interval after sorting
 Step 4: Iterate through remaining intervals starting from index 1
 Step 5: For each interval, check if it overlaps with the last interval in result
 Step 6: If overlapping, merge by updating the end time to maximum of both ends
 Step 7: If not overlapping, add the current interval to result array

Submitted Code :