6. Merge Intervals

6. Merge Intervals

Medium
47.0%
1.6k
arraysorting
Google, Amazon, Netflix, Meta (Facebook), Apple, Microsoft, Uber, Bloomberg, Airbnb, Stripe, Adobe, Salesforce, LinkedIn, Oracle

You’re interviewing for a backend/data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A large-scale marketplace or streaming platform needs to manage time-based records such as:

  • promotion windows for products
  • ad campaign schedules
  • CDN cache validity periods
  • content licensing time ranges
  • user availability slots for scheduling

These time ranges are stored as intervals, where each interval has a start time and an end time.

Because multiple teams publish schedules independently, the stored intervals may overlap. To improve performance and reporting accuracy, the platform wants to compress the schedule by merging all overlapping time ranges into the smallest set of non-overlapping intervals.

This is a common coding interview / DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given an array of intervals intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of the merged non-overlapping intervals.

Two intervals overlap if the start of one interval is less than or equal to the end of the other interval.

Input Format

  • intervals: a 2D array of integers where each entry is [start, end]

Output Format

  • Return a 2D array of merged intervals, sorted by start time

Examples

Example 1:

Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: [1,3] overlaps with [2,6], so they merge into [1,6]

Example 2:

Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: The intervals overlap because 4 touches 4 and should be merged.

Constraints

  • 1 <= intervals.length <= 100,000
  • 0 <= start_i <= end_i <= 100,000
  • Intervals may be unsorted
  • Output should contain the minimum number of intervals

Loading editor...

[[1,3],[2,6],[8,10],[15,18]]
[[1,6],[8,10],[15,18]]

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback