Why Intervals Are a Common Problem Pattern in DSA C# - Performance Analysis
Intervals problems often involve sorting and merging ranges. Understanding their time complexity helps us see how the solution scales with input size.
We want to know how the number of operations grows as we handle more intervals.
Analyze the time complexity of the following code snippet.
// Merge overlapping intervals
public int[][] Merge(int[][] intervals) {
Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0]));
List merged = new List();
foreach (var interval in intervals) {
if (merged.Count == 0 || merged[merged.Count - 1][1] < interval[0]) {
merged.Add(interval);
} else {
merged[merged.Count - 1][1] = Math.Max(merged[merged.Count - 1][1], interval[1]);
}
}
return merged.ToArray();
}
This code sorts intervals by start time, then merges overlapping ones into a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sorting the intervals and then iterating through them once.
- How many times: Sorting takes multiple comparisons (depends on n log n), then one loop runs once over all intervals (n times).
As the number of intervals grows, sorting takes more time, and merging grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 log 10 + 10 = 43 operations |
| 100 | About 100 log 100 + 100 = 700 operations |
| 1000 | About 1000 log 1000 + 1000 = 10,000 operations |
Pattern observation: The sorting dominates and grows faster than just looping; it grows roughly like n times log n.
Time Complexity: O(n log n)
This means as the number of intervals doubles, the time grows a bit more than double, mainly due to sorting.
[X] Wrong: "Merging intervals is just a simple loop, so it must be O(n)."
[OK] Correct: Sorting the intervals first takes more time than just looping, so the overall time is dominated by sorting, not just merging.
Understanding why intervals problems often require sorting helps you explain your approach clearly and shows you grasp the key cost drivers in your solution.
"What if the intervals were already sorted? How would the time complexity change?"
Practice
Solution
Step 1: Understand what intervals represent
Intervals represent ranges such as time periods or numeric ranges, common in scheduling and resource allocation.Step 2: Recognize real-world applications
Many problems like meeting rooms, calendar events, or booking systems use intervals to represent availability or usage.Final Answer:
Because many real-world problems involve ranges or periods of time -> Option DQuick Check:
Intervals = ranges in real life [OK]
- Assuming intervals always have fixed lengths
- Thinking intervals never overlap
- Believing intervals are sorted alphabetically
Solution
Step 1: Recall tuple syntax in C#
Tuples use parentheses with comma-separated values, optionally named like (start: 5, end: 10).Step 2: Check each option
var interval = (start: 5, end: 10); uses correct tuple syntax with named elements. Options A and C use invalid collection syntax. var interval = (5; 10); uses a semicolon which is invalid.Final Answer:
var interval = (start: 5, end: 10); -> Option AQuick Check:
Tuple syntax = parentheses with commas [OK]
- Using square brackets instead of parentheses
- Using braces which are for collections
- Separating tuple elements with semicolons
var intervals = new List<(int start, int end)> { (1, 3), (2, 6), (8, 10), (15, 18) };
var merged = new List<(int start, int end)>();
intervals.Sort((a, b) => a.start.CompareTo(b.start));
foreach (var interval in intervals) {
if (merged.Count == 0 || merged[^1].end < interval.start) {
merged.Add(interval);
} else {
merged[^1] = (merged[^1].start, Math.Max(merged[^1].end, interval.end));
}
}
foreach (var m in merged) {
Console.Write($"({m.start},{m.end}) ");
}Solution
Step 1: Sort intervals by start
Intervals sorted: (1,3), (2,6), (8,10), (15,18).Step 2: Merge overlapping intervals
First interval (1,3) added. Next (2,6) overlaps with (1,3), merge to (1,6). Then (8,10) no overlap, add. Then (15,18) no overlap, add.Final Answer:
(1,6) (8,10) (15,18) -> Option BQuick Check:
Merged intervals = (1,6), (8,10), (15,18) [OK]
- Not sorting intervals before merging
- Overwriting intervals incorrectly
- Printing original intervals without merging
bool Overlaps((int start, int end) a, (int start, int end) b) {
return a.end < b.start && b.end > a.start;
}Solution
Step 1: Understand overlap condition
Two intervals overlap if they share any points. The given condition checks for non-overlap incorrectly.Step 2: Correct the logic
Correct overlap check is !(a.end < b.start || b.end < a.start), meaning intervals do overlap if they are not completely apart.Final Answer:
The condition logic is reversed; it should check if intervals do not overlap -> Option AQuick Check:
Overlap means intervals share points, not separated [OK]
- Using && instead of || in condition
- Ignoring inclusive boundaries
- Returning wrong data type
Solution
Step 1: Sort intervals by start time
Sorting helps process meetings in chronological order.Step 2: Use a min-heap to track earliest ending meeting
For each meeting, if it starts after the earliest ending meeting, reuse room; else allocate new room. The heap size tracks rooms needed.Final Answer:
Sort intervals by start time, use a min-heap to track end times, count max concurrent meetings -> Option CQuick Check:
Min rooms = max concurrent meetings [OK]
- Merging intervals instead of counting overlaps
- Using stack which doesn't track end times properly
- Counting intervals with same start time only
Ready to prove it?
Pass the test and this pattern moves unknown
