Skip to content

Commit 473524c

Browse files
feat: add Non-overlapping Intervals explanation
- Greedy algorithm approach - Comprehensive problem analysis - Multiple approaches and optimizations - Edge cases and applications
1 parent 7c4ee64 commit 473524c

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Non-overlapping Intervals
2+
3+
## Problem Statement
4+
5+
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
6+
7+
## Examples
8+
9+
**Example 1:**
10+
```
11+
Input: intervals = [[1,2],[2,3],[3,4],[1,3]]
12+
Output: 1
13+
Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.
14+
```
15+
16+
## Approach
17+
18+
### Method 1: Greedy Algorithm (Recommended)
19+
1. Sort intervals by end time
20+
2. Use greedy approach to select non-overlapping intervals
21+
3. Count removed intervals
22+
4. Most efficient approach
23+
24+
**Time Complexity:** O(n log n) - Sorting
25+
**Space Complexity:** O(1) - In-place modification
26+
27+
### Method 2: Dynamic Programming
28+
1. Use DP to find maximum non-overlapping intervals
29+
2. Return total - maximum
30+
3. Less efficient than greedy approach
31+
32+
**Time Complexity:** O(n²) - Nested loops
33+
**Space Complexity:** O(n) - DP array
34+
35+
## Algorithm
36+
37+
```
38+
1. Sort intervals by end time
39+
2. Initialize count = 0, end = intervals[0][1]
40+
3. For i from 1 to n-1:
41+
a. If intervals[i][0] < end: count++
42+
b. Else: end = intervals[i][1]
43+
4. Return count
44+
```
45+
46+
## Key Insights
47+
48+
- **Greedy Choice**: Always select interval with earliest end time
49+
- **Local Optimum**: Maximum non-overlapping intervals
50+
- **Global Optimum**: Minimum intervals to remove
51+
- **Space Optimization**: Use only necessary space
52+
53+
## Alternative Approaches
54+
55+
1. **Dynamic Programming**: Use DP for maximum intervals
56+
2. **Sorting by Start**: Sort by start time and use different logic
57+
3. **Brute Force**: Try all possible combinations
58+
59+
## Edge Cases
60+
61+
- Empty intervals: Return 0
62+
- Single interval: Return 0
63+
- No overlaps: Return 0
64+
- All overlaps: Return n-1
65+
66+
## Applications
67+
68+
- Interval algorithms
69+
- Scheduling problems
70+
- Algorithm design patterns
71+
- Interview preparation
72+
- System design
73+
74+
## Optimization Opportunities
75+
76+
- **Greedy Algorithm**: Most efficient approach
77+
- **Space Optimization**: O(1) space complexity
78+
- **Logarithmic Time**: O(n log n) time complexity
79+
- **No Extra Space**: Use only necessary space

0 commit comments

Comments
 (0)