Greedy & Intervals
Data Structures & Algorithms · Greedy & Dynamic Programming · Intermediate · 15 min
Make the best local choice each step, and master meeting-room style problems.
Strips of coloured tape laid on a ruler. Once you slide them into order by where they start, you can walk left to right with one long strip in your hand, stretching it over every piece that touches it and starting a new strip only at a real gap.
The idea in everyday words
Paying with the fewest coins: always hand over the biggest coin that fits. That 'grab the best option right now' habit is greedy. It doesn't always work, but when it does, it's simple and fast.
Greedy in one example
Coins [25, 10, 5, 1], amount 63 → 25, 25, 10, 1, 1, 1 = 6 coins.
def coins(amount):
used = []
for c in [25, 10, 5, 1]:
while amount >= c:
amount -= c
used.append(c)
return used
print(coins(63))
Warning: with coins [4, 3, 1] and amount 6, greedy picks 4+1+1 (3 coins) but 3+3 is better → that needs DP.
Intervals: sort by start, then sweep
Meetings [[1,3],[2,6],[8,10]]. Sort by start. If the next meeting starts before the current one ends, they overlap → merge.
def merge(intervals):
intervals.sort(key=lambda x: x[0])
out = [intervals[0]]
for start, end in intervals[1:]:
if start <= out[-1][1]:
out[-1][1] = max(out[-1][1], end)
else:
out.append([start, end])
return out
print(merge([[1, 3], [2, 6], [8, 10], [9, 12]]))
Step by step
- Sort:
[[1,3],[2,6],[8,10]]
- [2,6]:
2 <= 3 → overlap → [1,6]
- [8,10]:
8 > 6 → new interval
- Result:
[[1,6],[8,10]]
Code example
def can_attend_all(meetings):
meetings.sort()
for i in range(1, len(meetings)):
if meetings[i][0] < meetings[i - 1][1]:
return False
return True
print(can_attend_all([[0, 30], [5, 10]]), can_attend_all([[7, 10], [2, 4]]))Complexity
- Time: O(n log n) for the sort
- Space: O(n)
Interview tips
Merge Intervals, Insert Interval, Meeting Rooms I/II, Non-overlapping Intervals.
Clarify: do touching intervals ([1,2],[2,3]) overlap?
Challenge: Merge Overlapping Intervals
Merge all overlapping intervals (touching counts as overlapping) and return them sorted by start.
Example: merge_intervals([[1,3],[2,6],[8,10]]) → [[1,6],[8,10]]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Merge Intervals (Medium)
- Insert Interval (Medium)
- Non-overlapping Intervals (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
More in Greedy & Dynamic Programming
Previous: Minimum Spanning Trees · Next: Dynamic Programming