Complete the code to declare a struct for an interval with start and end.
typedef struct {
int start;
int [1];
} Interval;The struct for an interval typically has 'start' and 'end' to mark boundaries.
Complete the code to check if two intervals overlap.
int isOverlap(Interval a, Interval b) {
return !(a.end <= b.[1] || b.end <= a.start);
}To check overlap, compare the end of one with the start of the other.
Fix the error in the function that merges two overlapping intervals.
Interval mergeIntervals(Interval a, Interval b) {
Interval merged;
merged.start = a.start < b.start ? a.start : b.[1];
merged.end = a.end > b.end ? a.end : b.end;
return merged;
}When merging, the start is the minimum of both starts.
Fill both blanks to create a function that sorts intervals by their start time.
int compareIntervals(const void *a, const void *b) {
Interval *i1 = (Interval *)[1];
Interval *i2 = (Interval *)[2];
return i1->start - i2->start;
}In qsort compare function, cast the void pointers to Interval pointers using 'a' and 'b'.
Fill all three blanks to create a function that merges a list of intervals.
int mergeAllIntervals(Interval intervals[], int n, Interval result[]) {
if (n == 0) return 0;
qsort(intervals, n, sizeof(Interval), compareIntervals);
int idx = 0;
result[idx] = intervals[0];
for (int i = 1; i < n; i++) {
if (result[idx].end >= intervals[i].[1]) {
if (result[idx].end < intervals[i].[2]) {
result[idx].end = intervals[i].[3];
}
} else {
idx++;
result[idx] = intervals[i];
}
}
return idx + 1;
}The function merges intervals by checking if current interval's start is within the last merged interval's end, then updates the end if needed.
