Reading history

Interval Problems in C: Merge Intervals, Activity Selection and Sweep Line

6 min read 1 views

Solve interval problems in C: merge overlapping intervals, pick the most activities greedily and count overlaps with a sweep line.

Many everyday problems are about time ranges. When is a doctor free? What is the largest number of talks you can attend at a festival? How many classrooms does a school need? Each range is an interval with a start and an end. Three techniques solve most interval problems: sorting them, a greedy choice, and a sweep line that walks through all start and end times in order.

In this lesson you will learn

  • Merging overlapping intervals
  • Activity selection: the greedy rule “earliest finish first”
  • Why that greedy rule is correct
  • Counting overlaps with a sweep line
  • Handling intervals that touch at their ends

You should know greedy algorithms and qsort in C.

Merging and Selecting Intervals

#include <stdio.h>
#include <stdlib.h>

typedef struct { int start, end; } Interval;     /* times as 24-hour numbers, e.g. 930 */

static int byStart(const void *a, const void *b) {
    return ((const Interval *)a)->start - ((const Interval *)b)->start;
}
static int byEnd(const void *a, const void *b) {
    return ((const Interval *)a)->end - ((const Interval *)b)->end;
}

/* 1. Merge overlapping intervals: sort by start, then extend or close */
int merge(Interval *v, int n, Interval *out) {
    qsort(v, n, sizeof *v, byStart);
    int k = 0;
    out[k] = v[0];
    for (int i = 1; i < n; i++) {
        if (v[i].start <= out[k].end) {                  /* overlaps the current block */
            if (v[i].end > out[k].end) out[k].end = v[i].end;
        } else out[++k] = v[i];                          /* gap: start a new block */
    }
    return k + 1;
}

/* 2. Activity selection: the most non-overlapping talks.
   Greedy rule: always take the talk that finishes first. */
int selectMax(Interval *v, int n, Interval *chosen) {
    qsort(v, n, sizeof *v, byEnd);
    int k = 0, lastEnd = -1;
    for (int i = 0; i < n; i++)
        if (v[i].start >= lastEnd) { chosen[k++] = v[i]; lastEnd = v[i].end; }
    return k;
}

int main(void) {
    Interval busy[] = { {900, 1030}, {1300, 1400}, {1000, 1100}, {1530, 1600},
                        {1345, 1500}, {1100, 1130} };
    int n = 6;
    Interval merged[6];
    int m = merge(busy, n, merged);
    printf("Busy blocks after merging:\n");
    for (int i = 0; i < m; i++) printf("  %04d-%04d\n", merged[i].start, merged[i].end);

    Interval talks[] = { {900, 1000}, {930, 1200}, {1000, 1030}, {1015, 1130},
                         {1030, 1130}, {1100, 1230}, {1200, 1300}, {1130, 1400} };
    Interval chosen[8];
    int c = selectMax(talks, 8, chosen);
    printf("Most talks you can attend: %d\n", c);
    for (int i = 0; i < c; i++) printf("  %04d-%04d\n", chosen[i].start, chosen[i].end);
    return 0;
}

Output

Busy blocks after merging:
  0900-1130
  1300-1500
  1530-1600
Most talks you can attend: 4
  0900-1000
  1000-1030
  1030-1130
  1200-1300
  • Times are stored as numbers like 930 for 9:30, so they sort in time order. %04d prints 900 as 0900.
  • Merging: sort by start time. Each next interval either overlaps the current block (its start is at or before the block’s end) and extends it, or starts a new block.
  • 10:00–11:00 and 11:00–11:30 touch exactly, and this code joins them because it uses <=. Use < if touching intervals should stay separate.
  • Activity selection: sort by end time, then take each talk that starts after the last chosen one ends. This picks 4 talks.
  • Why it works: the talk that ends first leaves the most time for everything after it. Any best plan can swap its first talk for this one without losing a talk.
  • Choosing the shortest talk, or the earliest start, does not always give the best answer.
9:0010:0011:0012:0013:0014:0015:0016:00inputmerged

Sweep Line: How Many Rooms?

#include <stdio.h>
#include <stdlib.h>

/* Sweep line: how many classrooms are needed so no two classes clash?
   Turn each class into two events: +1 at its start, -1 at its end.
   Sort the events by time and keep a running count. */
typedef struct { int time, delta; } Event;

static int cmp(const void *a, const void *b) {
    const Event *x = a, *y = b;
    if (x->time != y->time) return x->time - y->time;
    return x->delta - y->delta;            /* at equal times, an end (-1) comes first */
}

int main(void) {
    int cls[][2] = { {800, 930}, {830, 1000}, {900, 1030}, {930, 1100},
                     {1000, 1130}, {1100, 1200}, {845, 915} };
    int n = sizeof cls / sizeof cls[0];

    Event ev[2 * 7];
    for (int i = 0; i < n; i++) {
        ev[2 * i]     = (Event){ cls[i][0], +1 };
        ev[2 * i + 1] = (Event){ cls[i][1], -1 };
    }
    qsort(ev, 2 * n, sizeof *ev, cmp);

    int now = 0, best = 0, bestTime = 0;
    printf(" time  event  rooms in use\n");
    for (int i = 0; i < 2 * n; i++) {
        now += ev[i].delta;
        printf(" %04d  %-5s  %d\n", ev[i].time, ev[i].delta > 0 ? "start" : "end", now);
        if (now > best) { best = now; bestTime = ev[i].time; }
    }
    printf("Rooms needed: %d (first reached at %04d)\n", best, bestTime);
    return 0;
}

Output

 time  event  rooms in use
 0800  start  1
 0830  start  2
 0845  start  3
 0900  start  4
 0915  end    3
 0930  end    2
 0930  start  3
 1000  end    2
 1000  start  3
 1030  end    2
 1100  end    1
 1100  start  2
 1130  end    1
 1200  end    0
Rooms needed: 4 (first reached at 0900)
  • Each class becomes two events: +1 when it starts and -1 when it ends.
  • Sorting the events and keeping a running total gives the number of classes happening at each moment. The largest total is the number of rooms needed: 4.
  • At equal times, ends are sorted before starts. A class ending at 9:30 frees its room for a class starting at 9:30.
  • The sweep line takes O(n log n) for sorting and O(n) for the walk. Checking every pair of classes instead would take O(n2).
ProblemSort byThen
Merge overlapping intervalsStartExtend or start a new block
Most non-overlapping intervalsEndGreedily take the next one that fits
Fewest intervals to remove for no overlapsEndn minus the activity selection answer
Maximum overlap (rooms, platforms)Event timeRunning +1 / -1 count
Free time between meetingsStartMerge, then report the gaps

Common Mistakes

  1. Sorting by the wrong field: merging needs start times, activity selection needs end times.
  2. Not deciding how touching intervals behave, so < and <= are mixed up.
  3. Processing a start before an end at the same time in a sweep line, which counts one room too many.
  4. Comparing times as text, so “1000” sorts before “930”. Store times as numbers or minutes since midnight.

Practice Exercises

Exercise 1. Using the merged busy blocks 0900–1130, 1300–1500 and 1530–1600, list the free times between 0900 and 1700.

Show answer

1130–1300, 1500–1530 and 1600–1700. Each gap runs from the end of one block to the start of the next, plus the time after the last block.

Exercise 2. Trains arrive and leave a station at given times. How would you find the number of platforms needed?

Show answer

This is the same as the rooms problem. Create a +1 event at each arrival and a -1 event at each departure, sort them, and track the largest running total. Decide whether a train leaving at the same minute another arrives frees the platform in time, and order the events to match.

Frequently Asked Questions

What if talks have different values and I want the most total value?

Then the greedy rule no longer works. This is weighted interval scheduling, solved with dynamic programming: sort by end time and, for each talk, choose the better of skipping it or taking it plus the best answer for talks that end before it starts.

Can the sweep line handle millions of intervals?

Yes. It needs only one sort and one pass, so it handles millions of events in well under a second in C.

Summary

  • Sort by start to merge overlapping intervals.
  • Sort by end and pick greedily to fit the most non-overlapping intervals.
  • A sweep line with +1 and -1 events finds the maximum overlap in O(n log n).
  • Decide carefully how intervals that touch at their ends should behave.

Next: Convex Hull in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *