MediumArraySortingIntervals

Merge Intervals

LeetCode
1 approach, code in all languages

You are given a collection of intervals where each entry is written as a pair [start, end]. Some of these ranges may touch or overlap one another. Your task is to fuse every group of connected ranges into a single interval so that no two ranges in the result share any common ground.

Return a fresh list containing only the merged, non-overlapping intervals, and the intervals may be returned in any order that the checker accepts (sorted by start is the natural choice).

Example 1

Input: intervals = [[1,4],[3,6],[8,10],[9,12]]

Output: [[1,6],[8,12]]

1-4 and 3-6 touch, so they collapse into 1-6; 8-10 and 9-12 collapse into 8-12.

Example 2

Input: intervals = [[2,3],[3,5]]

Output: [[2,5]]

The two ranges meet exactly at 3, which still counts as overlapping, so they merge.

Constraints

  • 1 ≤ intervals.length ≤ 10^4
  • intervals[i].length == 2
  • 0 ≤ start ≤ end ≤ 10^4
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now