Level Up Your Coding Skills & Crack Interviews — Save up to 50% or more on Educative.io Today! Claim Discount

Arrow
Table of contents

Intervals

Intervals pattern shows up constantly in interview questions because real life is full of “ranges”: meetings on a calendar, CPU tasks running over time, booking windows, delivery slots, availability blocks, and numeric segments in arrays.

Many interval problems look like they require heavy pairwise comparisons, but they rarely do. Once you sort by start time, you can usually scan in one pass and make decisions locally using a simple overlap condition. That single change turns messy problems into structured ones.

What is the Intervals pattern?

An interval is a range defined by a start and an end, such as [10, 20]. The Intervals pattern is a way to reason about problems where you are given many ranges and asked to merge them, detect conflicts, find gaps, compute intersections, or measure how much they overlap.

Instead of comparing every interval with every other interval, the approach is to sort the intervals by start time, keep one interval as the “current” active interval, and scan from left to right while applying a consistent rule. This works because sorting gives you an order where future intervals can only interact meaningfully with the interval you’re currently tracking.

Overlap rule

The most common overlap rule treats two intervals as overlapping when the next interval begins before the current one ends, meaning next.start <= current.end. Under this rule, even “touching” intervals like [1,2] and [2,3] count as overlapping and will be merged. However, not all problems define overlap the same way, and some treat touching intervals as separate. In those cases the condition becomes next.start < current.end. The main habit to build is to always align your overlap rule with the problem statement.

Why this pattern works

Sorting by start time gives you a powerful guarantee: while scanning left to right, the only interval that can overlap the next one is the interval you’re currently tracking. Any earlier interval that could overlap would already have been merged into the current interval. This prevents backtracking and removes the need for nested loops.

That guarantee is why interval problems often become clean and predictable after sorting. You repeatedly compare your current interval with the next interval, update state if they overlap, and otherwise finalize the current interval and move forward.

Core relationships between Intervals

When you compare a current interval with the next interval, they usually fall into one of three relationships. The first is non-overlapping, where there is a gap between them. This happens when next.start > current.end, meaning the next interval starts strictly after the current interval finishes. In scheduling problems, this gap often represents free time; in merging problems, it means you should output the current interval and begin tracking the next one.

The second relationship is overlapping, which occurs when next.start <= current.end under the common default rule. In this case the intervals collide, so you may merge them, treat them as a conflict, or compute something about their shared portion depending on the question.

The third relationship is containment, where one interval is fully inside another. This happens when next.end <= current.end, meaning the current interval already covers the next interval completely. In merge-style problems, containment usually means you don’t need to change the start or end of the current interval; you simply continue scanning.

1 / 3

The standard “Sort + Sweep” template

Most merge-style interval problems follow the same high-level structure. You sort intervals by start time, then initialize a current interval as the first one. As you scan, if the next interval overlaps with current, you extend current’s end to the maximum of the two ends. If the next interval does not overlap, you commit the current interval to the output and then set current to the next interval. After the loop finishes, you must also add the last tracked current interval, because it won’t be added inside the loop.

This template is extremely reusable. The only thing that changes across problems is what you “output” or what you “track” as state: sometimes it’s merged intervals, sometimes it’s a count of conflicts, sometimes it’s free slots, and sometimes it’s a running maximum of overlap.

Common strategies built on Intervals

A classic use of this pattern is merging overlapping intervals (also called union or compression). After sorting, whenever the next interval starts before the current one ends, you merge by extending the current end to the maximum of both ends. This produces a compressed set of intervals that cover the same total range without redundancy.

1 / 7

Another common variation is computing intersections, where you want the shared overlap between ranges. When two intervals overlap, their intersection is formed by taking the later start and the earlier end, which becomes [max(start1, start2), min(end1, end2)]. This is frequently used for finding common availability between schedules.

Intervals are also used to detect gaps or free time. After sorting busy times, any time you see that the next interval starts after the current interval ends, you have found an empty space between them. That space is a candidate free slot, and the exact boundaries depend on whether endpoints are inclusive or exclusive in the problem.

1 / 7

For problems involving the maximum number of overlaps (such as minimum meeting rooms), a sweep-line style variant is common. You treat each start as increasing active usage and each end as decreasing it, then scan events in order to track the maximum number of simultaneous intervals. The main tricky detail here is handling ties correctly when a start and end share the same timestamp, which depends on whether touching counts as overlapping.

1 / 6

How to recognize an Intervals problem

  • Input is a list of ranges like [start, end], time windows, numeric segments, or coverage blocks.
  • The question depends on how ranges relate (their relative positions matter).
  • Keywords/clues in the prompt: overlap, merge, intersection, gaps, containment, conflicts and scheduling
  • Sorting by start would likely make the solution much simpler (often required).
  • A brute-force idea would compare many pairs, but sorting + one scan can reduce the work dramatically.

Common mistakes and how to avoid them

  • Sorting mistakes: Not sorting first, or sorting by the wrong field. For most interval problems, sorting by start is what makes the scan logic correct.
  • Overlap boundary bugs: Using the wrong overlap condition especially with “touching” intervals. You must decide whether boundaries count as overlapping, because < vs <= changes results.
  • End-of-loop + normalization oversights: People often forget to output the final current interval after the loop (dropping the last merge). Also, if input validity isn’t guaranteed, normalize intervals so start ≤ end before processing.

Frequently Asked Questions

Why do we sort?

Sorting by start ensures that when you’re scanning, the only interval that can overlap the next one is your current merged interval—no need to look back.

Can Intervals ever be O(n)?

Yes, if intervals are already sorted (common in “insert interval” problems), the scan is O(n).

What if I need the minimum number of meeting rooms?

That’s still an Intervals problem, but you typically use a min-heap of end times or a sweep line rather than merging.

How do I handle “touching” intervals?

Match the problem statement. If [1,2] and [2,3] should merge, use <=. Otherwise use <.

Share with others:

Unlock up to 68% off lifetime access to Coding Interview prep with Educative

Getting ready for coding interviews or sharpening your problem-solving skills? Unlock a lifetime discount with comprehensive resources designed to help you master technical interviews.

Data structures and algorithms

Pattern-based problem solving

Mock interview practice

Real-world coding challenges

Coding Interview Logo