Interval problems: merging and scheduling

Master the interval pattern to solve merging, scheduling, and overlapping problems using sorting and greedy techniques.

intermediate14 min readBy CureBugs EditorialUpdated 5 Nov 2026

Intervals represent ranges of values, most commonly defined by a start time and an end time. Whether you are building a calendar application that highlights conflicting meetings, allocating CPU time slots in an operating system, or matching riders with drivers in a specific time window, you are dealing with intervals. In coding interviews, interval problems are a staple. They test your ability to reason about overlapping boundaries, apply sorting algorithms effectively, and use greedy strategies to optimize resource allocation. While these problems can seem tricky at first glance, they almost always boil down to a single, predictable pattern: sorting the intervals and iterating through them to resolve overlaps.

When to use this pattern

Interval problems are usually easy to spot. The input is almost always an array or list of pairs, such as [[1, 3], [2, 6], [8, 10]].

Look for these specific signals in the problem statement:

  • Keywords: "merge", "overlap", "schedule", "insert", "minimum rooms", "maximum events", "conflicts".
  • Scenarios: Calendar bookings, meeting rooms, task scheduling, video playback segments, or any scenario involving a timeline.
  • Objectives: You are asked to combine overlapping ranges, find gaps between ranges, determine the maximum number of non-overlapping ranges, or calculate the peak number of simultaneous events.

The core idea

The fundamental challenge with intervals is that they can appear in any order. If you try to compare every interval against every other interval to check for overlaps, you will end up with an inefficient O(N^2) algorithm.

The core idea of the interval pattern is to bring related intervals together by sorting them.

Once the intervals are sorted (usually by their start time), any overlapping intervals will be adjacent to each other in the array. This allows you to solve the problem in a single pass O(N) after the initial sort O(N log N).

Here is how the logic flows when merging intervals:

  1. Sort the array of intervals based on the start time.
  2. Create an empty list to hold the merged intervals.
  3. Iterate through the sorted intervals.
  4. For each interval, compare its start time with the end time of the last interval in your merged list.
  5. The Overlap Condition: If current.start <= last.end, they overlap! Update the end time of the last interval to be the maximum of both end times.
  6. If they don't overlap, simply append the current interval to the merged list.

Template

This is the foundational template for merging intervals. Memorize this structure, as it forms the basis for almost all interval-related interview questions.

def merge_intervals(intervals):
    if not intervals:
        return []
        
    # 1. Sort by start time
    intervals.sort(key=lambda x: x[0])
    
    # 2. Initialize the result list with the first interval
    merged = [intervals[0]]
    
    # 3. Iterate through the remaining intervals
    for i in range(1, len(intervals)):
        last_merged = merged[-1]
        current = intervals[i]
        
        # 4. Check for overlap
        if current[0] <= last_merged[1]:
            # Merge by updating the end time
            last_merged[1] = max(last_merged[1], current[1])
        else:
            # No overlap, add to result
            merged.append(current)
            
    return merged

Worked examples

Let's apply this pattern to three classic interview problems that frequently appear in rounds at top tech companies in India, from startups like Swiggy and Cred to MNCs like Amazon and Google.

Example 1: Insert Interval

Problem: You are given an array of non-overlapping intervals sorted by their start time. You are also given a newInterval. Insert the newInterval into the intervals, merging if necessary, so that the resulting intervals are still sorted and non-overlapping.

Approach: Since the input array is already sorted, we do not need to sort it again. This means we can optimize our solution from O(N log N) down to O(N). We can break the problem into three distinct phases:

  1. Before the overlap: Add all intervals that end before the new interval starts. These definitely don't overlap.
  2. During the overlap: As long as the current interval overlaps with the new interval, merge them by updating the start and end times of the newInterval.
  3. After the overlap: Add all remaining intervals.
def insert(intervals, newInterval):
    result = []
    i = 0
    n = len(intervals)
    
    # Phase 1: Add intervals that come completely before the newInterval
    while i < n and intervals[i][1] < newInterval[0]:
        result.append(intervals[i])
        i += 1
        
    # Phase 2: Merge overlapping intervals
    while i < n and intervals[i][0] <= newInterval[1]:
        newInterval[0] = min(newInterval[0], intervals[i][0])
        newInterval[1] = max(newInterval[1], intervals[i][1])
        i += 1
    result.append(newInterval)
    
    # Phase 3: Add the remaining intervals
    while i < n:
        result.append(intervals[i])
        i += 1
        
    return result

Complexity:

  • Time Complexity: O(N) because we iterate through the array of N intervals exactly once.
  • Space Complexity: O(N) to store the result array (or O(1) auxiliary space if we don't count the output array).

Example 2: Meeting Rooms II

Problem: Given an array of meeting time intervals where intervals[i] = [start_i, end_i], return the minimum number of conference rooms required.

Approach: This is a classic scheduling problem. Instead of merging intervals, we need to find the maximum number of overlapping intervals at any given point in time.

A highly elegant way to solve this is using the Chronological Ordering (or Two Pointers) approach. We separate the start times and end times into two different arrays and sort them individually.

Think of it as a physical room: every time a meeting starts, someone walks in (we need a room). Every time a meeting ends, someone walks out (a room is freed). By comparing the next start time with the next end time, we can track the active number of rooms.

def minMeetingRooms(intervals):
    if not intervals:
        return 0
        
    # Extract and sort start and end times separately
    starts = sorted([i[0] for i in intervals])
    ends = sorted([i[1] for i in intervals])
    
    rooms = 0
    end_ptr = 0
    
    # Iterate through all start times
    for start in starts:
        # If a meeting starts before the earliest ending meeting finishes,
        # we need an additional room.
        if start < ends[end_ptr]:
            rooms += 1
        else:
            # Otherwise, a previous meeting has ended, so we can reuse its room.
            # We move the end pointer to track the next earliest ending meeting.
            end_ptr += 1
            
    return rooms

Complexity:

  • Time Complexity: O(N log N) because sorting the start and end arrays dominates the O(N) two-pointer traversal.
  • Space Complexity: O(N) to store the separate starts and ends arrays.

Example 3: Non-overlapping Intervals (Activity Selection)

Problem: Given an array of intervals, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Approach: This problem introduces a crucial variation: Sorting by End Time.

If we want to maximize the number of non-overlapping intervals (which is the same as minimizing removals), we should always greedily pick the interval that ends the earliest. Why? Because an interval that ends early leaves the maximum possible room for subsequent intervals.

  1. Sort the intervals by their end time.
  2. Keep track of the current_end of the last valid interval we included.
  3. Iterate through the intervals. If an interval starts before current_end, it overlaps, and we must remove it (increment a counter).
  4. If it starts on or after current_end, we keep it and update current_end to this interval's end time.
def eraseOverlapIntervals(intervals):
    if not intervals:
        return 0
        
    # CRITICAL: Sort by END time
    intervals.sort(key=lambda x: x[1])
    
    removals = 0
    current_end = intervals[0][1]
    
    for i in range(1, len(intervals)):
        if intervals[i][0] < current_end:
            # Overlap found, we must remove this interval
            removals += 1
        else:
            # No overlap, update the end time
            current_end = intervals[i][1]
            
    return removals

Complexity:

  • Time Complexity: O(N log N) due to the sorting step.
  • Space Complexity: O(1) auxiliary space (though the sorting algorithm itself may use O(log N) or O(N) depending on the language implementation).

Variations and pitfalls

Interval problems are heavily reliant on sorting, but the way you sort and compare determines your success. Here is a quick cheat sheet for the different sorting strategies:

Problem GoalSorting StrategyWhy it worksExample Problem
Merging intervalsSort by Start TimeBrings overlapping intervals adjacent to each other, making a single pass possible.Merge Intervals
Max non-overlappingSort by End TimeGreedy choice: finishing an event as early as possible leaves the most room for future events.Activity Selection
Min/Max concurrent eventsSeparate Start/End arraysWe only care about the chronological sequence of events (start = +1 room, end = -1 room).Meeting Rooms II

Pitfall 1: Open vs. Closed bounds

Does [1, 2] overlap with [2, 3]?

  • If the bounds are inclusive (closed), they touch at 2. Depending on the problem, this might count as an overlap.
  • If the bounds are exclusive (open), they do not overlap.

Always clarify this with your interviewer before writing code. In most LeetCode-style problems, touching intervals (like [1, 2] and [2, 3]) can be merged into [1, 3], but for scheduling problems (like Meeting Rooms), a meeting ending at 2:00 PM and another starting at 2:00 PM do not require two separate rooms. Notice how in our Meeting Rooms II code, we used start < ends[endPtr] (strictly less than) to account for this.

Pitfall 2: Language-specific sorting space complexity

Interviewers at companies like Amazon and Microsoft care deeply about space complexity. When you say your algorithm takes O(1) space because you sort in-place, be careful:

  • Python: list.sort() uses Timsort, which takes O(N) space in the worst case.
  • Java: Arrays.sort() on objects uses Timsort (O(N) space), but on primitives it uses Dual-Pivot Quicksort (O(log N) space).
  • C++: std::sort uses Introsort, which takes O(log N) space.
  • JavaScript: Array.prototype.sort() depends on the engine (V8 uses Timsort, O(N) space).

If you want true O(1) auxiliary space, you must explicitly mention these language-specific nuances to your interviewer.

Practice checklist

To truly master the interval pattern, you should be able to solve these problems without looking at the template. Start with the basics and work your way up to the greedy variations.

  1. Merge Intervals (Classic sorting by start time)
  2. Insert Interval (Optimizing for already sorted inputs)
  3. Meeting Rooms (Checking for any overlap)
  4. Meeting Rooms II (Chronological ordering / Min-Heap)
  5. Non-overlapping Intervals (Greedy sorting by end time)
  6. Minimum Number of Arrows to Burst Balloons (Another excellent greedy variation)

Happy coding, and remember: when in doubt, sort it out!

Mock interview

Solve one like this with an interviewer watching

Getting the answer alone is half the round. The other half is clarifying the problem, explaining your approach, coding while you talk and handling the follow-up. Try it on a problem you haven't seen.

  • A timed problem in a real editor, judged on hidden tests
  • Hints if you ask, and they count against you like they would in the room
  • A scored report that quotes your answers and says what to fix
Start a mock coding round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
DSA patterns•intermediate

The two pointers pattern

15 min read
DSA patterns•intermediate

The sliding window pattern

11 min read
DSA patterns•intermediate

Prefix sums and hashing

11 min read
DSA patterns•intermediate

The monotonic stack pattern

12 min read
Interval problems: merging and scheduling · CureBugs