Insert Interval
Insert newInterval into sorted intervals array, merging overlaps intervals is sorted and non-overlapping Example: [[1,3],[6,9]], [2,5] => [[1,5],[6,9]]
Given an array of non-overlapping integer intervals sorted by start value and a new interval [start,end], return the sorted list after inserting the new interval and merging every overlap. Each interval has start <= end, and both endpoints are included, so intervals sharing an endpoint must merge. The input array may be empty, in which case return an array containing the new interval.
Examples
You write
insert(intervals: List[List[int]], newInterval: List[int])
Example 1
- Input
- [[1,3],[6,9]], [2,5]
- returns
- [[1,5],[6,9]]
Example 2
- Input
- [[1,2],[3,5],[6,7],[8,10],[12,16]], [4,8]
- returns
- [[1,2],[3,10],[12,16]]
The pattern behind it
Arrays & Hashing
I reach for it when
- You catch yourself scanning the array again for every element.
- The problem asks about duplicates, pairs, counts or groups.
Say this before you type. Say what the key is and what the value remembers, before you write the loop.
All 127 Arrays & Hashing problemsIntervals
I reach for it when
- The input is ranges: meetings, bookings or segments.
- The question asks about overlaps, merges or gaps.
Say this before you type. Say what you sort by, and whether two ranges that touch count as overlapping.
All 6 Intervals problems
Meet Coco
Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.