Merge overlapping intervals in a collection of ranges
Reported in Monzo European engineering loops. Sort-and-sweep array problem common in calendar and scheduling interviews.
Interview scenario
Context for Monzo candidates:
Input: [[1,3],[2,6],[8,10],[15,18]]. Output merged non-overlapping intervals.
Model answer
Try answering aloud first
Cover trade-offs, structure, and a concrete example before revealing the baseline response.
How to frame this at Monzo: Connect your answer to measurable impact, clarity of thought, and trade-offs the team cares about. Below is a strong baseline response you can adapt with your own project examples.
Sort intervals by start time. Iterate: if current interval overlaps last merged (start ≤ last end), extend last end; else append new interval.
function merge(intervals) {
if (!intervals.length) return [];
intervals.sort((a, b) => a[0] - b[0]);
const out = [intervals[0]];
for (let i = 1; i < intervals.length; i++) {
const [s, e] = intervals[i];
const last = out[out.length - 1];
if (s <= last[1]) last[1] = Math.max(last[1], e);
else out.push([s, e]);
}
return out;
}Time O(n log n) for sort, O(n) scan. Space O(n) for output.
Follow-ups: insert interval into sorted list, meeting rooms minimum count (min-heap on end times), and interval intersection of two lists.
Discussion
Comments (0)
Share how this question came up in your loop, or add tips for others preparing.
Log in to comment on this question.