1. Append and Run Merge Intervals (Brute Force)
Intuition
Add newInterval to the list, sort by start time, and merge overlapping intervals.
Algorithm
- 1. Append newInterval to intervals.
- 2. Sort intervals based on interval[0].
- 3. Loop through intervals: - if result is empty or result.back()[1] < current[0]: add current - else: result.back()[1] = max(result.back()[1], current[1]).
- 4. Return result.
Brute Force Append, Full Sort & Merge Intervals
2 of 2 questions left todayPhase 1 — Step 1: Step 1: Append [4, 8] to the list and sort all 6 intervals by start time
Phase 1 — Step 1: Step 1: Append [4, 8] to the list and sort all 6 intervals by start time. Sorting costs O(N log N).
#include <iostream>#include <vector>#include <algorithm>using namespace std; // Brute Force Approach: Append and Merge Intervalsvector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) { intervals.push_back(newInterval); sort(intervals.begin(), intervals.end()); vector<vector<int>> merged; for (const auto& interval : intervals) { if (merged.empty() || merged.back()[1] < interval[0]) { merged.push_back(interval); } else { merged.back()[1] = max(merged.back()[1], interval[1]); } } return merged;} int main() { vector<vector<int>> intervals = {{1, 3}, {6, 9}}; vector<int> newInterval = {2, 5}; vector<vector<int>> result = insert(intervals, newInterval); cout << "Output: ["; for (int i = 0; i < result.size(); i++) { cout << "[" << result[i][0] << ", " << result[i][1] << "]" << (i + 1 < result.size() ? ", " : ""); } cout << "]" << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Sorting N+1 intervals takes O(N log N). The merging pass takes O(N). - Space complexity:
O(N)— Output list holds up to N+1 intervals.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.