MEDIUM NC#130 Blind #35 Intervals

57. Insert Interval

๐Ÿ“– Problem

You are given an array of non-overlapping intervals where intervals[i] = [start_i, end_i] sorted in ascending order by start_i, and a new interval newInterval = [start, end], insert newInterval into intervals if still sorted in ascending order by start_i and intervals still does not have any overlapping intervals (merge overlapping if needed). Return intervals after insertion.

๐Ÿง  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

  • โ†’ Add all intervals ending before new interval
  • โ†’ Merge all overlapping intervals
  • โ†’ Add all remaining intervals after new interval
  • โ†’ Time: O(n), Space: O(n) for result

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขAdd all intervals ending before new interval
  • โ€ขMerge all overlapping intervals
  • โ€ขAdd all remaining intervals after new interval

Common Pitfalls

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

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
insert([[1,3],[6,9]], [2,5]);
Expected:
[[1,5], [6,9]]
Test Case 2
Not run
Input:
insert([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]);
Expected:
[[1,2], [3,10], [12,16]]
Test Case 3
Not run
Input:
insert([], [5,7]);
Expected:
[[5,7]]

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

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