DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES
Merge Overlapping Intervals
Learn how to merge overlapping intervals using a clear C program.
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
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
[1,6] [8,10] [15,18]
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- After sorting by start time, extend the current interval or begin a new merged interval.
- 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.
