Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an interval struct with start and end.
DSA C++
struct Interval {
int [1];
int end;
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'begin' or 'left' instead of 'start' which is the conventional name.
✗ Incorrect
The interval struct commonly uses 'start' to represent the beginning of the interval.
2fill in blank
mediumComplete the code to sort intervals by their start time.
DSA C++
bool compareIntervals(const Interval &a, const Interval &b) {
return a.[1] < b.start;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing by 'end' instead of 'start' which changes the sorting order.
✗ Incorrect
Sorting intervals by their 'start' time helps in many interval problems.
3fill in blank
hardFix the error in the code to merge overlapping intervals.
DSA C++
vector<Interval> mergeIntervals(vector<Interval> &intervals) {
if (intervals.empty()) return {};
sort(intervals.begin(), intervals.end(), compareIntervals);
vector<Interval> merged;
merged.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (merged.back().end >= intervals[i].[1]) {
merged.back().end = max(merged.back().end, intervals[i].end);
} else {
merged.push_back(intervals[i]);
}
}
return merged;
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing end with end instead of end with start causes wrong merging.
✗ Incorrect
To check overlap, compare the end of last merged interval with the start of current interval.
4fill in blank
hardFill both blanks to create a map of intervals keyed by their start time and storing their end time.
DSA C++
map<int, int> intervalMap = {
{intervals[0].[1], intervals[0].[2]
};Attempts:
3 left
💡 Hint
Common Mistakes
Using 'length' or 'duration' which are not fields in the struct.
✗ Incorrect
The map keys intervals by their start and stores the end as value.
5fill in blank
hardFill all three blanks to create a vector of intervals from two separate vectors of starts and ends.
DSA C++
vector<Interval> createIntervals(const vector<int> &starts, const vector<int> &ends) {
vector<Interval> intervals;
for (int i = 0; i < starts.size(); i++) {
intervals.push_back([1], [2]);
}
sort(intervals.begin(), intervals.end(), [3]);
return intervals;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using intervals[i] inside push_back or wrong comparator in sort.
✗ Incorrect
We use starts[i] and ends[i] to create intervals and sort them using compareIntervals.
