Skip to content
Learn Netverks
Company prep Infosys
Junior (1–3 years) Coding / DSA Medium

Merge overlapping intervals in a collection of ranges

Reported in Infosys interview loops. Sort-and-sweep array problem common in calendar and scheduling interviews.

Role
SDE
Location
Chennai

Context for Infosys candidates:

Input: [[1,3],[2,6],[8,10],[15,18]]. Output merged non-overlapping intervals.

Try answering aloud first

Cover trade-offs, structure, and a concrete example before revealing the baseline response.

Spoiler-free prep mode

How to frame this at Infosys: 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.

Comments (0)

Share how this question came up in your loop, or add tips for others preparing.

Log in to comment on this question.