When a coding interview asks you to work with time slots, numeric ranges, or any start‑end pair, the intervals pattern is usually the right tool. The pattern isn’t a magic trick; it’s a disciplined way to turn a messy list of ranges into something you can reason about with a few simple steps.

Recognizing the Intervals Signal

Look for keywords that describe a range:

  • "start" and "end" (or "left"/"right", "low"/"high").
  • Phrases like "meeting rooms", "calendar", "flight schedule", "range of values", or "segments".
  • Questions that ask for "overlaps", "gaps", "merging", "covering", or "minimum number of resources".

When you see any of these, pause and ask yourself: Can I treat each item as an interval and sort them? If the answer is yes, you’re likely in the intervals pattern.

Core Steps of the Pattern

  1. Parse into a uniform structure – usually a tuple (start, end).
  2. Sort – most problems require sorting by the start coordinate; tie‑break on end if needed.
  3. Iterate – walk the sorted list, maintaining a running state (e.g., current merged interval, active count, heap of ends).
  4. Update answer – depending on the goal, you might merge intervals, count overlaps, or track a maximum.
  5. Return – format the result as required (list of intervals, integer count, etc.).

These steps are flexible. For example, a problem that asks for the minimum number of meeting rooms replaces step 4 with a heap that tracks the earliest finishing meeting.

Worked Example: Merging Overlapping Intervals

Problem: Given a list of closed intervals [[1,3],[2,6],[8,10],[15,18]], merge all overlapping intervals and return the resulting list.

Python Solution

from typing import List

def merge(intervals: List[List[int]]) -> List[List[int]]:
    if not intervals:
        return []
    # 1. Sort by start time
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for cur in intervals[1:]:
        prev = merged[-1]
        # 2. If current start is within previous interval, merge
        if cur[0] <= prev[1]:
            prev[1] = max(prev[1], cur[1])
        else:
            merged.append(cur)
    return merged

Explanation

  • Sorting ensures we only need to look at the previous interval to decide if there is an overlap.
  • The if cur[0] <= prev[1] check captures the inclusive nature of closed intervals.
  • Updating prev[1] in‑place keeps the algorithm O(1) extra space (aside from the output list).

Complexity

  • Time: O(N log N) for sorting, plus O(N) for the linear scan.
  • Space: O(N) for the output; the algorithm itself uses constant auxiliary space.

Common Pitfalls and How to Avoid Them

PitfallWhy it HappensFix
Forgetting to sortThe algorithm assumes chronological order; unsorted input leads to missed merges.Always sort first; write a comment reminding yourself.
Using < instead of <= for closed intervalsOverlap at a single point is missed, yielding extra intervals.Match the interval type (closed vs. half‑open) in the condition.
Modifying the original list unintentionallyIn‑place changes can surprise later code or test harnesses.Work on a copy or document that you mutate in‑place deliberately.
Off‑by‑one errors in heap‑based room‑count problemsThe heap stores end times; pushing/popping at the wrong moment miscounts rooms.Push the end time after checking the earliest finishing meeting.
Ignoring empty inputEdge case not covered leads to runtime errors.Guard with if not intervals: return [].

Five Representative Practice Problems

Below are five problems that each highlight a different twist on the intervals pattern. The descriptions are original; the hints steer you toward the right approach without giving away the full solution.

#Problem ThemeCore TwistHint
1Maximum Overlap – Find the point where the most intervals overlap.Use a sweep line with start/end events.Turn each interval into two events (+1 at start, -1 at end) and sort them.
2Minimum Meeting Rooms – Compute the fewest rooms needed for a set of meetings.Maintain a min‑heap of end times.When a new meeting starts, compare its start with the smallest end in the heap.
3Insert and Merge – Insert a new interval into a list and merge if needed.Combine insertion with the merge pass.Insert the new interval, then run the standard merge algorithm.
4Interval Intersection – Return the intersection of two interval lists.Two‑pointer traversal of sorted lists.Advance the pointer of the interval that ends earlier after recording any overlap.
5Covering Points – Choose the smallest set of points that hits all intervals.Greedy selection of the rightmost end of the current interval.Sort by end, then pick the end of the first interval and discard all intervals it covers.

Quick Walk‑through of Problem 2 (Minimum Meeting Rooms)

  1. Sort the meetings by start time.
  2. Iterate through the sorted list, pushing each meeting’s end time onto a min‑heap.
  3. Before pushing, pop from the heap while the smallest end time is ≤ the current start – those rooms are now free.
  4. The heap size after each insertion is the number of rooms in use; track the maximum size.
  5. Return the maximum heap size.

The same skeleton works for many variants, such as "maximum concurrent events" or "minimum number of platforms for a railway station".

Complexity Overview Across Variants

  • Sorting‑dominant problems (merge, insert‑and‑merge, intersection) share O(N log N) time.
  • Sweep‑line or heap problems (max overlap, meeting rooms) also start with O(N log N) due to sorting; the heap operations add another O(N log N) in the worst case but are often linear in practice.
  • Greedy point‑cover is O(N log N) for sorting, then O(N) for the single pass.
  • Space is typically O(N) for the output; auxiliary space is O(N) for heaps or O(1) for in‑place merges.

When Not to Use the Intervals Pattern

If the problem talks about subarrays, substrings, or graph paths, the interval metaphor may mislead. Also, when the input size is tiny (e.g., ≤ 5) and the interview focuses on brute‑force reasoning, a full sort might be overkill. In those cases, discuss the trade‑off and propose a simpler approach.

How to Practice This

  1. Pick one problem a day from the list above. Write the solution from scratch, then run it against edge cases (empty list, single interval, fully overlapping set).
  2. Explain the algorithm aloud as if you were in an interview. Use Call Assistant to capture your explanation and get instant feedback on clarity and pacing.
  3. Swap the data structure: replace a list with a heap, or change the sorting key. Observe how the change affects both code and complexity; this deepens your intuition for when each variant is appropriate.

FAQ

  • Q: How do I decide between a heap and a simple counter for overlap problems? A: Use a heap when you need to know the earliest finishing interval (e.g., meeting rooms). A counter works for sweep‑line approaches where you only need the net change at each event.

  • Q: Why is sorting by start time usually enough? A: After sorting, any overlap can only involve the current interval and the most recent one(s). This eliminates the need for nested loops and reduces the problem to a linear scan.

  • Q: Can I solve interval problems without sorting? A: In special cases with limited range (e.g., timestamps within a day) you can use counting sort or bucket techniques, but sorting remains the most general and clear method.

  • Q: What’s the biggest mistake candidates make with the intervals pattern? A: Forgetting to handle the inclusive/exclusive nature of interval boundaries, which leads to off‑by‑one errors and incorrect merge results.

Frequently asked questions

How do I decide between a heap and a simple counter for overlap problems?

Use a heap when you need to know the earliest finishing interval, such as allocating meeting rooms. A counter works for sweep‑line approaches where you only track the net change at each event.

Why is sorting by start time usually enough?

Sorting guarantees that any overlap can only involve the current interval and the most recent one(s), turning a potentially quadratic check into a linear scan.

Can I solve interval problems without sorting?

If the domain is small (e.g., minutes in a day), counting sort or bucket arrays can replace the general sort, but sorting remains the most flexible and readable solution.

What’s the biggest mistake candidates make with the intervals pattern?

Missing the inclusive/exclusive boundary rules, which creates off‑by‑one errors and yields extra or missing intervals after merging.

#coding pattern#intervals#algorithm#interview prep#python