Problem
FAANG · LeetCode #57

Insert Interval — three-stage drill

1The ProblemMedium

Insert Interval

Insert a new interval into a sorted, non-overlapping list — merge what it touches.

insert one new interval into a sorted, non-overlapping list — merge where it touchesintervals[1,2][3,5][6,7][8,10][12,16]new[4,8]0246810121416result[1,2][3,10][12,16]return[[1,2],[3,10],[12,16]]
Examples
intervals=[[1,2],[3,5],[6,7],[8,10],[12,16]], new=[4,8]→ [[1,2],[3,10],[12,16]]intervals=[[1,3],[6,9]], new=[2,5]→ [[1,5],[6,9]]

constraintInput list is already sorted by start and has no internal overlaps; merge only happens against the new interval.

2The PatternTIME O(n log n) · SPACE O(n)

Intervals

Given a pile of ranges, sort them by start — now any overlap is a neighbour, so a single left→right pass handles them.

sort the ranges by start, then sweep once01234567891011[7,9][2,5][1,3][8,10]given: a pile of ranges in any order
Problems using this pattern
3The SolutionRESULT → [[1,2],[3,10],[12,16]]

Step through it

given — a sorted list + one new interval to insertintervals[1,2][3,5][6,7][8,10][12,16]new[4,8]0246810121416result
given: 5 sorted, non-overlapping intervals · insert the orange interval [4, 8]
Step 1 / 8
Arrow keys to navigate · escape to reset

All problems by pattern

Backtracking

Recursive Descent