MEDIUM NC#131 Blind #36 Intervals

56. Merge Intervals

๐Ÿ“– Problem

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

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Sort intervals by start time
  • โ†’ If current interval overlaps with last merged, merge them
  • โ†’ Otherwise, add current interval to result
  • โ†’ Time: O(n log n), Space: O(n) for result

๐Ÿงญ Prerequisites

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขSort intervals by start time
  • โ€ขIf current interval overlaps with last merged, merge them
  • โ€ขOtherwise, add current interval to result

Common Pitfalls

  • โ€ขTime: O(n log n), Space: O(n) for result

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
merge([[1,3],[2,6],[8,10],[15,18]]);
Expected:
[[1,6], [8,10], [15,18]]
Test Case 2
Not run
Input:
merge([[1,4],[4,5]]);
Expected:
[[1,5]]
Test Case 3
Not run
Input:
merge([[1,4],[0,4]]);
Expected:
[[0,4]]

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit