To address common interval-related programming problems (since the original problem statement was an image), here are solutions to three frequent ones:
1. Merge Overlapping Intervals
Problem: Given an array of intervals, merge all overlapping intervals and return the merged list.
Approach:
- Sort intervals by start time.
- Iterate and merge adjacent overlapping intervals.
Solution Code:
def merge(intervals):
if not intervals:
return []
intervals.sort()
merged = [intervals[0]]
for current in intervals[1:]:
last = merged[-1]
if current[0] <= last[1]:
last[1] = max(last[1], current[1]) # Merge
else:
merged.append(current) # Add non-overlapping
return merged
Explanation:
- Sorting ensures overlapping intervals are adjacent.
- Merge by updating the end time of the last interval if current starts before/at its end.
- Time complexity: O(n log n) (sorting), Space: O(n) (result list).
2. Maximum Non-Overlapping Intervals
Problem: Select the maximum number of non-overlapping intervals.
Approach:
- Sort intervals by end time (to prioritize earliest ending intervals).
- Pick intervals that don’t overlap with the last selected one.
Solution Code:
def max_non_overlapping(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[1])
count = 1
last_end = intervals[0][1]
for s, e in intervals[1:]:
if s >= last_end:
count +=1
last_end = e
return count
Explanation:
- Choosing earliest ending intervals maximizes room for subsequent intervals.
- Time complexity: O(n log n), Space: O(1) (excluding input).
3. Minimum Meeting Rooms
Problem: Find the minimum number of conference rooms needed for meetings.
Approach:
- Separate start/end times and sort both.
- Use two pointers to track active rooms (increment if start < end, else free a room).
Solution Code:
def min_meeting_rooms(intervals):
starts = sorted([i[0] for i in intervals])
ends = sorted([i[1] for i in intervals])
rooms = 0
end_ptr = 0
for s in starts:
if s < ends[end_ptr]:
rooms +=1
else:
end_ptr +=1
return rooms
Explanation:
- Sorting start/end times allows efficient tracking of room usage.
- Time complexity: O(n log n), Space: O(n) (for start/end lists).
Choose the solution that matches your problem! If the original problem differs, share the text statement for a precise answer.
Let me know if you need further clarification.


作者声明:本文包含人工智能生成内容。