1. Compare Every Pair for Overlap
Intuition
Compare every pair of intervals (i, j) to check if interval i and interval j overlap.
Algorithm
- 1. Let n = intervals.length.
- 2. For i from 0 to n-1: - For j from i+1 to n-1: - If max(intervals[i][0], intervals[j][0]) < min(intervals[i][1], intervals[j][1]), return false.
- 3. If no overlaps found, return true.
All Pairs Overlap Comparison (O(N^2))
2 of 2 questions left todayPhase 1 — Pair (0, 1): Compare intervals[0] = [0, 30] and intervals[1] = [5, 10]
Phase 1 — Pair (0, 1): Compare intervals[0] = [0, 30] and intervals[1] = [5, 10]. Check overlap: max(0, 5) < min(30, 10) => 5 < 10 is TRUE!
#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: bool canAttendMeetings(vector<vector<int>>& intervals) { int n = intervals.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (max(intervals[i][0], intervals[j][0]) < min(intervals[i][1], intervals[j][1])) { return false; } } } return true; }}; int main() { Solution sol; vector<vector<int>> intervals = {{0, 30}, {5, 10}, {15, 20}}; bool ans = sol.canAttendMeetings(intervals); cout << "Can Attend Meetings: " << (ans ? "true" : "false") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Nested loops test all N*(N-1)/2 pairs in O(N2) time. - Space complexity:
O(1)— Auxiliary space is O(1).
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.