Skip to content
Visual explainer 5h to learn 4 steps

Greedy & intervals

Solve interval scheduling and greedy choice problems.

By Invicly Tech, , in Interview Preparation. About 12 minutes to read.

Topic 13 of 27

In short

A greedy algorithm makes the locally best choice at each step and never revisits it. It is fast and simple, but only correct when a local choice can be proven safe; intervals are the classic case.

Explained simply

A greedy algorithm makes the choice that looks best right now and never changes its mind. When you give change in cash, you hand over the biggest note that fits, then the next biggest, and so on. For normal currency, that simple habit gives the fewest notes and coins.

Greedy is fast and the code is short, often a sort followed by one loop. The catch is that it is not always right. With coins of 1, 3 and 4, making 6 the greedy way gives 4 + 1 + 1, but 3 + 3 uses fewer coins. Greedy only works when you can argue that the local best choice never hurts later.

Intervals are where greedy shines. An interval is a start and an end, like a meeting from 9:00 to 10:30. Questions ask you to merge overlapping meetings, fit in as many as possible, count how many rooms you need, or remove the fewest so none overlap.

For almost every interval problem, the first step is to sort, either by start time or by end time. Choosing the right one is most of the solution.

Press Play on a diagram to walk through it one step at a time.

FlowMerge intervals
  1. 1
    Sort by start

    O(n log n), overlapping intervals become adjacent

  2. 2
    Take the first

    It starts the output list

  3. 3
    Overlaps last?

    start <= end of the last merged interval

  4. 4
    Extend or append

    Overlap: extend end. Otherwise: new interval

  5. 5
    Return merged

    One pass after sorting

CompareGreedy vs dynamic programming
Greedy
  • One choice per step, no going back
  • Often sort then scan
  • Needs a proof it is safe
  • Usually O(n log n) or O(n)
Dynamic programming
  • Considers all choices per state
  • Stores subproblem answers
  • Always correct if states are right
  • Usually slower
FlowNon-overlapping Intervals: [1,2], [2,3], [3,4], [1,3]
  1. 1
    Sort by end

    [1,2], [2,3], [1,3], [3,4]

  2. 2
    Keep [1,2]

    Last end = 2

  3. 3
    Keep [2,3]

    Starts at 2, not before 2; last end = 3

  4. 4
    Remove [1,3]

    Starts at 1, before 3: removals = 1

  5. 5
    Keep [3,4]

    Answer: remove 1 interval

In depth

Proving a greedy choice is safe

Interviewers may ask "why does greedy work here?" The usual answer is an exchange argument. Take any optimal solution. Find the first place it differs from the greedy one, and swap in the greedy choice. Show the result is still valid and no worse. Repeat, and the optimal solution turns into the greedy one, so greedy must be optimal too.

For picking the most non-overlapping meetings: greedy picks the meeting that ends first. Any optimal plan has some first meeting. Replace it with the earliest-ending one: it ends no later, so it cannot clash with anything after it. Nothing is lost. Before you rely on greedy, also try to break it with two or three tiny examples.

  • Exchange: swapping in the greedy choice never hurts
  • Stays ahead: greedy is never behind at any step
  • Always test small counterexamples first

Sort by start, or sort by end?

Sort by start when you need to combine intervals or sweep through time in order. Merge Intervals and Insert Interval sort by start, so overlapping intervals become neighbours. Sort by end when you want to keep as many intervals as possible. Non-overlapping Intervals (fewest removals), Minimum Number of Arrows to Burst Balloons and classic activity selection keep the one that ends first, because it leaves the most room for the rest.

Meeting Rooms II (how many rooms are needed) sorts by start and keeps a min-heap of the end times of rooms in use. If the earliest end is at or before the new start, that room is free and reused; otherwise a new room opens. The heap size at the end is the answer.

CompareWhich sort key?
Sort by start
  • Merge Intervals
  • Insert Interval
  • Meeting Rooms II (plus a heap)
  • Sweep through time in order
Sort by end
  • Non-overlapping Intervals
  • Minimum Arrows for Balloons
  • Max number of meetings
  • Earliest finish leaves most room

Jump Game I and II

In Jump Game, nums[i] is the longest jump from index i. Track farthest, the furthest index you can reach so far. Walk left to right: if i ever becomes greater than farthest, you are stuck and the answer is false. Otherwise update farthest = max(farthest, i + nums[i]). One pass, O(n), no DP needed.

Jump Game II asks for the fewest jumps. Think of it as BFS in levels without a queue. The indices reachable with one jump form a window; keep the end of the current window and the farthest reach from inside it. When i reaches the current end, you must jump: count one jump and set the end to the farthest reach. This is also O(n) and is a nice example of greedy that behaves like BFS.

Gas Station, step by step

There are n stations in a circle; gas[i] is what you collect at station i and cost[i] is what it takes to reach the next one. First, if the total gas is less than the total cost, no start works: return -1. Otherwise exactly one answer is guaranteed by the problem.

To find it, drive from station 0 keeping a tank total. If the tank goes negative after station i, then no station from the current start up to i can be the answer: each of them would reach i with no more gas than you had. So restart at i + 1 with an empty tank. The last start you set is the answer. One pass, O(n) time, O(1) space.

FlowGas Station scan
  1. 1
    Check totals

    Total gas below total cost: return -1

  2. 2
    Drive forward

    tank += gas[i] - cost[i]

  3. 3
    Tank negative?

    No start from here to i can work

  4. 4
    Restart

    start = i + 1, tank = 0

  5. 5
    Return start

    The last restart point is the answer

Edge cases interviewers watch for

Ask whether touching intervals overlap. In Merge Intervals, [1, 2] and [2, 3] merge into [1, 3], so the test is start <= last end. In Non-overlapping Intervals they do not clash, so you keep both. In Meeting Rooms a meeting ending at 10 frees the room for one starting at 10. One wrong comparison operator changes the answer.

Other traps: forgetting max() when extending a merge, so a short interval inside a long one cuts the end short; sorting by the wrong key; returning early on an empty input; and modifying the input array when the caller did not expect it. Saying these out loud shows care.

Learn it in 4 short steps

About 1h 15m each. Track them with a timer in your plan.

  1. 1
    Learn when greedy choice is safe~1h 15m
  2. 2
    Sort and merge intervals~1h 15m
  3. 3
    Practice: Merge Intervals, Non-overlapping Intervals~1h 15m
  4. 4
    Practice: Jump Game, Gas Station~1h 15m

Key points

  • Sort intervals by start to merge, or by end to pick the most non-overlapping ones.
  • Non-overlapping Intervals: keep the interval that ends first, remove the others.
  • Jump Game: track the farthest reachable index in one O(n) pass.
  • Test greedy ideas on small counterexamples; Coin Change with odd coins breaks greedy.

Key terms

Tap a card to flip it. 0/4 known

Examples

python
def merge(intervals):
    intervals.sort(key=lambda iv: iv[0])
    out = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= out[-1][1]:            # overlaps
            out[-1][1] = max(out[-1][1], end)
        else:
            out.append([start, end])
    return out  # O(n log n) for the sort

Meeting Rooms II: [[0, 30], [5, 10], [15, 20]]

Sort by start (already sorted). Meeting 0 to 30: no rooms yet, open one; the heap of end times is {30}. Meeting 5 to 10: the earliest end is 30, after 5, so open a second room: {10, 30}. Meeting 15 to 20: the earliest end is 10, at or before 15, so that room is free: remove 10 and add 20: {20, 30}. Two rooms are in use, so the answer is 2. Sorting is O(n log n) and each heap step is O(log n).

java
int minMeetingRooms(int[][] meetings) {
    Arrays.sort(meetings, (a, b) -> Integer.compare(a[0], b[0]));  // by start
    PriorityQueue<Integer> ends = new PriorityQueue<>();  // end times of busy rooms
    for (int[] m : meetings) {
        if (!ends.isEmpty() && ends.peek() <= m[0]) ends.poll();  // reuse a free room
        ends.offer(m[1]);
    }
    return ends.size();
}

Gas Station: gas [1, 2, 3, 4, 5], cost [3, 4, 5, 1, 2]

Gas minus cost at each station: -2, -2, -2, 3, 3. The total is 0, which is not negative, so an answer exists. Start at 0: the tank is -2, so restart at 1. Again -2, restart at 2. Again -2, restart at 3. Now the tank goes 3, then 6, and never drops below zero. The answer is station 3. Check: from 3 you have 4 - 1 = 3, then 3 + 5 - 2 = 6, then 6 + 1 - 3 = 4, then 4 + 2 - 4 = 2, then 2 + 3 - 5 = 0, and you are back.

java
int canCompleteCircuit(int[] gas, int[] cost) {
    int total = 0, tank = 0, start = 0;
    for (int i = 0; i < gas.length; i++) {
        int diff = gas[i] - cost[i];
        total += diff;
        tank += diff;
        if (tank < 0) {       // cannot get past i from start
            start = i + 1;    // so no station from start to i works
            tank = 0;
        }
    }
    return total >= 0 ? start : -1;
}

Quick reference

  • Merge Intervals: sort by start; overlap when start <= last end; extend with max()
  • Most intervals kept (or fewest removed): sort by end and keep the earliest finisher
  • Meeting Rooms II: sort by start, min-heap of end times; the answer is the heap size
  • Jump Game: farthest = max(farthest, i + nums[i]); fail if i > farthest
  • Gas Station: total gas below total cost means -1; else restart after each negative tank
  • Before trusting greedy, try three or four tiny counterexamples by hand
  • Ask whether touching intervals like [1, 2] and [2, 3] count as overlapping

Common mistakes

  • Using greedy without checking a counterexample.
  • Sorting by the wrong key for the problem.
  • Forgetting max() when extending, so a contained interval shrinks the end.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1To keep the largest number of non-overlapping meetings, how should you sort them?

Question 2

2How many rooms does Meeting Rooms II need for [[1, 5], [2, 6], [5, 7]]?

Question 3

3What does Jump Game return for [3, 2, 1, 0, 4]?

Question 4

4In Gas Station, why can you skip every station between the start and i when the tank goes negative at i?

Question 5

5Which problem is NOT solved correctly by a simple greedy rule?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Assign Cookies: each child needs a cookie of at least their greed size. Each cookie goes to at most one child. Maximise the number of happy children.

  2. Exercise 2medium

    Minimum Number of Arrows to Burst Balloons: each balloon spans [start, end] on a line, and an arrow at x bursts every balloon with start <= x <= end. Find the fewest arrows.

  3. Exercise 3hard

    Candy: children stand in a line with ratings. Each gets at least one candy, and a child with a higher rating than a neighbour must get more than that neighbour. Find the minimum total.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How do I know if a problem needs greedy or DP?
Try to break the greedy idea with a tiny example. If you find a case where the local best choice leads to a worse total, you need DP. If you cannot, and you can explain why swapping in the greedy choice never hurts, greedy is likely right.
Do I have to prove my greedy solution in an interview?
Not formally, but give a short reason, such as "the meeting that ends first leaves the most room for the rest". That sentence shows you did not just guess.
Why do almost all interval problems start with sorting?
Unsorted intervals can overlap in any order, so you would have to compare every pair, which is O(n^2). Sorting puts related intervals next to each other, and one linear scan finishes the job.

Go deeper

ShareXLinkedInWhatsApp