1. Graph of Overlapping Intervals / Nested Merges
Intuition
Iteratively compare pairs of intervals and merge any overlapping pair until no more merges can occur.
Algorithm
- 1. Maintain a list of intervals.
- 2. Repeatedly scan all pairs (i, j). If intervals[i] and intervals[j] overlap, merge them into intervals[i] and remove intervals[j].
- 3. Repeat until a full pass makes 0 merges.
- 4. Return merged intervals list.
Brute Force Pairwise Overlap Graph Merging
2 of 2 questions left todayCompare Intervals 0 and 1: [1, 3] and [2, 6] overlap because 2 <= 3
Compare Intervals 0 and 1: [1, 3] and [2, 6] overlap because 2 <= 3. Merge them into [1, 6].
#include <iostream>#include <vector>#include <string>#include <algorithm>#include <unordered_map>#include <unordered_set>#include <queue>#include <stack>#include <numeric>#include <climits> using namespace std; class Solution {public: vector<vector<int>> merge(vector<vector<int>>& intervals) { bool merged = true; while (merged) { merged = false; for (size_t i = 0; i < intervals.size(); ++i) { for (size_t j = i + 1; j < intervals.size(); ++j) { if (max(intervals[i][0], intervals[j][0]) <= min(intervals[i][1], intervals[j][1])) { intervals[i][0] = min(intervals[i][0], intervals[j][0]); intervals[i][1] = max(intervals[i][1], intervals[j][1]); intervals.erase(intervals.begin() + j); merged = true; break; } } if (merged) break; } } return intervals; }}; int main() { Solution sol; vector<vector<int>> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}}; vector<vector<int>> res = sol.merge(intervals); cout << "Merged Intervals:" << endl; for (const auto& interval : res) { cout << "[" << interval[0] << ", " << interval[1] << "] "; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Repeated pair scanning and list modifications can take up to O(N2) time. - Space complexity:
O(N)— Requires extra memory to manage dynamically mutating lists of 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.