In interval problems on LeetCode, the sorting strategy depends on what you're trying to achieve:
Sort by Start Time
Use this when you need to:
- Process intervals in chronological order
- Merge overlapping intervals
- Check for conflicts/overlaps
Common problems:
- Merge Intervals: Sort by start to easily identify overlapping intervals as you traverse
- Insert Interval: Sort by start to find the correct insertion position
- Meeting Rooms I/II: Sort by start to check conflicts in chronological order
- Employee Free Time: Sort by start to find gaps between intervals
Example pattern:
intervals.sort(key=lambda x: x[0]) # Sort by start
for interval in intervals:
if not merged or merged[-1][1] < interval[0]:
merged.append(interval)
else:
merged[-1][1] = max(merged[-1][1], interval[1])
Sort by End Time
Use this when you need to:
- Maximize the number of non-overlapping intervals (greedy approach)
- Minimize removals to avoid overlaps
- Select activities that finish earliest
Common problems:
- Non-overlapping Intervals: Sort by end to greedily select intervals that finish earliest
- Minimum Number of Arrows to Burst Balloons: Sort by end to find optimal arrow positions
- Maximum Number of Events That Can Be Attended: Sort by end for greedy selection
Example pattern:
intervals.sort(key=lambda x: x[1]) # Sort by end
count = 0
end = float('-inf')
for interval in intervals:
if interval[0] >= end: # No overlap
count += 1
end = interval[1]
Key Insight
- Sort by start: When you need to process/merge intervals or detect overlaps in sequence
- Sort by end: When you need to greedily select the maximum number of non-overlapping intervals (activity selection problem)
The choice often comes down to whether you're doing a sweep-line algorithm (sort by start) or a greedy selection algorithm (sort by end).