You keep a day's schedule as a list of busy blocks — [start, end] time ranges that are already sorted by start time and never overlap each other. Someone books a new meeting, and you need to slot it in: drop the new block into the right place, fuse it with any blocks it now overlaps, and hand back the updated schedule still sorted and still non-overlapping. Implement intervalsMergeNew(intervals, newInterval), which inserts one [start, end] into an already-sorted, non-overlapping list and returns the merged result. This is the classic "insert interval" problem; note it differs from merging an unsorted pile from scratch — here the existing list is already clean, and you only need a single linear pass.
// intervals: Array<[number, number]>
// A list of [start, end] pairs, SORTED by start and NON-OVERLAPPING
// (no two existing intervals touch or overlap). May be empty.
// newInterval: [number, number]
// The interval to insert. start <= end. CLOSED: it includes both endpoints.
// returns: Array<[number, number]>
// A NEW array, sorted by start and non-overlapping, with newInterval merged in.
// Touching at an endpoint counts as overlapping: inserting [3, 5] next to an
// existing [1, 3] yields [1, 5], because they share the point 3.
function intervalsMergeNew(intervals, newInterval): Array<[number, number]>;
// The new interval [4, 9] overlaps [3, 5], [6, 7], and [8, 10], so all three
// fuse with it into one expanded block. The flanking blocks stay put.
intervalsMergeNew(
[[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]],
[4, 9],
);
// → [[1, 2], [3, 10], [12, 16]]
// [3,5]+[6,7]+[8,10] all merge with [4,9] → [3, 10].
// The new interval [3, 5] falls in the gap between [1, 2] and [6, 8],
// overlapping nothing. It's simply placed in order.
intervalsMergeNew([[1, 2], [6, 8]], [3, 5]);
// → [[1, 2], [3, 5], [6, 8]]
// Touching at an endpoint merges (closed intervals): [3, 5] meets [1, 3] at 3.
intervalsMergeNew([[1, 3], [6, 9]], [3, 5]);
// → [[1, 5], [6, 9]]
[1, 3] and [3, 5] share the point 3, so they merge into [1, 5]. A one-unit gap — [1, 2] next to [4, 6] — does not merge; 2 and 4 are distinct points.intervals, its inner pairs, nor newInterval should change — return fresh arrays.start > end, or non-numeric coordinates — those are out of scope.