DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES

Merge Overlapping Intervals

Learn how to merge overlapping intervals using a clear C program.

AdvancedIntervalsSortingGreedy merge

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
[1,6] [8,10] [15,18]

COMPLETE C PROGRAM

Complete C implementation

dsa-merge-overlapping-intervals.c
Open in compiler
#include <stdio.h>

struct Interval { int start; int end; };

int main(void)
{
    struct Interval intervals[] = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
    int count = 4, write = 0;
    for (int index = 1; index < count; index++) {
        if (intervals[index].start <= intervals[write].end) {
            if (intervals[index].end > intervals[write].end) intervals[write].end = intervals[index].end;
        } else intervals[++write] = intervals[index];
    }
    for (int index = 0; index <= write; index++)
        printf("[%d,%d] ", intervals[index].start, intervals[index].end);
    putchar('\n');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

[1,6] [8,10] [15,18]
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. After sorting by start time, extend the current interval or begin a new merged interval.
  3. Display the computed result.

After sorting by start time, extend the current interval or begin a new merged interval.

EFFICIENCY

Time and space complexity

Time complexity

O(n log n) including sorting

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.