DSA · Patterns, not puzzles

How do you solve interval problems?

MediumintervalssortinggreedyUpdated Oct 2026
Quiz this track

Short answer

Sort intervals by start time, then sweep while merging overlapping ranges or counting active intervals. For meeting-room and scheduling problems, sorting by end time often supports a greedy choice.

Intervals are pairs of start and end values. The first decision is the sort key. Merging overlapping intervals sorts by start. Maximizing non-overlapping intervals sorts by end. Using the wrong key leads to a correct-looking loop with the wrong answer.

js
function mergeIntervals(intervals) {
  if (intervals.length === 0) return [];
  const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
  const result = [sorted[0]];

  for (let i = 1; i < sorted.length; i++) {
    const current = sorted[i];
    const last = result[result.length - 1];
    if (current[0] <= last[1]) {
      last[1] = Math.max(last[1], current[1]);
    } else {
      result.push(current);
    }
  }

  return result;
}
Sorting by start makes overlap detection local to the previous merged interval.

The main variants

  • Merge overlapping intervals: sort by start and extend the last end
  • Insert an interval: find the insertion point, then merge neighbours
  • Meeting rooms: sort starts and ends separately, then sweep
  • Maximum non-overlapping intervals: sort by end and take the earliest finishing
  • Intersection of two interval lists: use two pointers

Decide whether touching intervals count as overlapping. The condition current[0] <= last[1] treats a shared endpoint as overlap; current[0] < last[1] treats it as separate. State the convention before coding.

Sorting mutates the input array unless you copy it first. If the caller needs the original order, copy before sorting or store the original index.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why does merging sort by start time?
  2. 2Why does maximum non-overlap sort by end time?
  3. 3How do you insert a new interval into a sorted list?
  4. 4How do you find the minimum number of meeting rooms?

Say it in the interview

For merging intervals I sort by start and compare each interval with the last merged one. If it overlaps, I extend the end to the maximum; otherwise I start a new interval. For scheduling problems I often sort by end time because finishing earlier leaves more room. I clarify whether touching endpoints count as overlap, and I copy the input before sorting if the caller still needs the original order.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.