Hint: Think of joining overlapping time slots into one [OK]
Common Mistakes:
Confusing merging with sorting
Thinking it removes intervals instead of combining
Assuming it finds max length only
2. Which of the following C++ code snippets correctly sorts a vector of intervals by their start time before merging?
easy
A. std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[0] < b[0]; });
B. std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[1] > b[1]; });
C. std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[1] < b[1]; });
D. std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[0] > b[0]; });
Solution
Step 1: Identify sorting by start time
We need to sort intervals by their first element (start time) in ascending order.
Step 2: Check lambda comparator correctness
std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[0] < b[0]; }); uses a lambda that compares a[0] < b[0], which sorts ascending by start time correctly.
Final Answer:
std::sort(intervals.begin(), intervals.end(), [](auto &a, auto &b) { return a[0] < b[0]; }); -> Option A
Quick Check:
Sort by start ascending = a[0] < b[0] [OK]
Hint: Sort intervals by start ascending using a lambda [OK]
Common Mistakes:
Sorting by end time instead of start time
Sorting in descending order
Using default sort without comparator on vector of vectors
3. What is the output of the following C++ code that merges overlapping intervals?