cswork / templatesOpen the Line 500 list

STOP 08 · LINEAR STRUCTURES

Greedy Algorithms and Scheduling

Sort by end time, keep what fits O(n log n) time

Contest ratings Rating 1303–Rating 2260· median Rating 1681(15 of 25 problems rated by zerotrac)

Open the Line 500 list · stop 08 · 25 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 6 companies · in 6 reportsAmazon 1, Apple 1, DoorDash 1, LinkedIn 1, Microsoft 1

Warm up with this one

LC 455Assign CookiesEasy
Stuck? Peek at the approach

Sort demands and resources, satisfying the smallest remaining demand with the smallest usable resource.

Key points

  1. Always take the interval that ends first; it leaves the most room. Exchange argument: the first pick of any optimal answer can be swapped for it without loss.
  2. Minimum removals = total minus the maximum kept; "minimum arrows" is the same loop, except that touching endpoints count as overlapping.
  3. Before writing a greedy, state why the local choice never hurts; if you can't, the problem probably needs DP.

Common pitfalls

  • Sorting by start time lets one long interval that starts early block everything else.
  • Whether touching endpoints overlap depends on the problem; >= versus > is one character and a different answer.
  • A comparator written as a[1] - b[1] overflows near ±2^31.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Interval greedy · keep the earliest finish

How many intervals can you keep with no overlap (touching ends are fine)?

Try your own input
1–4#0
3–5#1
0–6#2
5–7#3
3–9#4
6–10#5
8–11#6
CurrentDiscovered / computedAnswer
Kept
0
Last end
−∞

The intervals are sorted by right end; each row of the chart is one interval.

InvariantExchange argument: the first interval of any optimal answer can be swapped for the one that ends first, with no loss.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 455, with it.

Python
def max_non_overlapping(intervals: list[list[int]]) -> int:
    """Most intervals you can keep with no overlap; [a, b] and [b, c] may touch."""
    count, end = 0, float("-inf")
    for start, finish in sorted(intervals, key=lambda iv: iv[1]):
        if start >= end:  # fits after the last kept interval
            count += 1
            end = finish
    return count
C++
// Most intervals you can keep with no overlap; [a, b] and [b, c] may touch.
int maxNonOverlapping(vector<vector<int>> intervals) {
    sort(intervals.begin(), intervals.end(),
         [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
    int count = 0;
    long long end = LLONG_MIN;
    for (auto& iv : intervals)
        if (iv[0] >= end) {  // fits after the last kept interval
            count++;
            end = iv[1];
        }
    return count;
}
Java
class Solution {
    // Most intervals you can keep with no overlap; [a, b] and [b, c] may touch.
    int maxNonOverlapping(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
        int count = 0;
        long end = Long.MIN_VALUE;
        for (int[] iv : intervals)
            if (iv[0] >= end) { // fits after the last kept interval
                count++;
                end = iv[1];
            }
        return count;
    }
}
Go
import (
	"math"
	"sort"
)

// maxNonOverlapping returns the most intervals you can keep with no overlap;
// [a, b] and [b, c] may touch.
func maxNonOverlapping(intervals [][]int) int {
	sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] })
	count, end := 0, math.MinInt
	for _, iv := range intervals {
		if iv[0] >= end { // fits after the last kept interval
			count++
			end = iv[1]
		}
	}
	return count
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Reach frontier: jump level by levelO(n) time · O(1) space

When each position says how far it can jump and the question is whether the end is reachable or how few jumps it takes: track how far the next jump could reach, and when i hits the current jump's boundary, count a jump and move the boundary there. It is BFS without a queue. LC 45 (Jump Game II); LC 55 only checks that the reach never falls behind i.

Python
def min_jumps(nums: list[int]) -> int:
    """Fewest jumps from index 0 to the last; nums[i] is the longest jump from i (LC 45)."""
    jumps = end = far = 0  # indexes up to end take `jumps` jumps; far: the next jump's reach
    for i in range(len(nums) - 1):
        far = max(far, i + nums[i])
        if i == end:  # this jump's range is used up: take another
            jumps += 1
            end = far
    return jumps
C++
// Fewest jumps from index 0 to the last; nums[i] is the longest jump from i (LC 45).
int minJumps(const vector<int>& nums) {
    int jumps = 0, end = 0, far = 0;  // indexes up to end take `jumps` jumps; far: the next jump's reach
    for (int i = 0; i + 1 < (int)nums.size(); i++) {
        far = max(far, i + nums[i]);
        if (i == end) {  // this jump's range is used up: take another
            jumps++;
            end = far;
        }
    }
    return jumps;
}
Java
class Solution {
    // Fewest jumps from index 0 to the last; nums[i] is the longest jump from i (LC 45).
    int minJumps(int[] nums) {
        int jumps = 0, end = 0, far = 0; // indexes up to end take `jumps` jumps; far: the next jump's reach
        for (int i = 0; i + 1 < nums.length; i++) {
            far = Math.max(far, i + nums[i]);
            if (i == end) { // this jump's range is used up: take another
                jumps++;
                end = far;
            }
        }
        return jumps;
    }
}
Go
// minJumps returns the fewest jumps from index 0 to the last; nums[i] is the longest jump from i.
func minJumps(nums []int) int {
	jumps, end, far := 0, 0, 0 // indexes up to end take `jumps` jumps; far: the next jump's reach
	for i := 0; i+1 < len(nums); i++ {
		far = max(far, i+nums[i])
		if i == end { // this jump's range is used up: take another
			jumps++
			end = far
		}
	}
	return jumps
}
Regret heap: take it, then drop the worst when overO(n log n) time · O(n) space

Scan by deadline (or position), take each item at first, and when a limit is broken, drop the costliest item taken so far, found in O(log n) with a heap. LC 630 (Course Schedule III), LC 1642 (Furthest Building You Can Reach) and LC 871 (Minimum Number of Refueling Stops) are this take-back greedy.

Python
import heapq


def schedule_course(courses: list[list[int]]) -> int:
    """Most courses [duration, last day] you can finish one at a time (LC 630)."""
    taken: list[int] = []  # chosen durations as a max-heap (negated)
    day = 0
    for duration, last in sorted(courses, key=lambda c: c[1]):  # earliest deadline first
        heapq.heappush(taken, -duration)
        day += duration
        if day > last:  # past the deadline: drop the longest course taken so far
            day += heapq.heappop(taken)
    return len(taken)
C++
// Most courses {duration, last day} you can finish one at a time (LC 630).
int scheduleCourse(vector<pair<int, int>> courses) {
    sort(courses.begin(), courses.end(), [](auto& a, auto& b) { return a.second < b.second; });  // earliest deadline first
    priority_queue<int> taken;  // chosen durations, longest on top
    long long day = 0;
    for (auto [duration, last] : courses) {
        taken.push(duration);
        day += duration;
        if (day > last) {  // past the deadline: drop the longest course taken so far
            day -= taken.top();
            taken.pop();
        }
    }
    return taken.size();
}
Java
class Solution {
    // Most courses {duration, last day} you can finish one at a time (LC 630).
    int scheduleCourse(int[][] courses) {
        int[][] sorted = courses.clone();
        Arrays.sort(sorted, Comparator.comparingInt(c -> c[1])); // earliest deadline first
        PriorityQueue<Integer> taken = new PriorityQueue<>(Comparator.reverseOrder()); // longest on top
        long day = 0;
        for (int[] c : sorted) {
            taken.offer(c[0]);
            day += c[0];
            if (day > c[1]) day -= taken.poll(); // past the deadline: drop the longest course taken so far
        }
        return taken.size();
    }
}
Go
import (
	"container/heap"
	"sort"
)

// maxHeap is a max-heap of ints for container/heap.
type maxHeap []int

func (h maxHeap) Len() int           { return len(h) }
func (h maxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h maxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *maxHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *maxHeap) Pop() any {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

// scheduleCourse returns the most courses {duration, last day} you can finish one at a time (LC 630).
func scheduleCourse(courses [][2]int) int {
	sorted := append([][2]int(nil), courses...)
	sort.Slice(sorted, func(i, j int) bool { return sorted[i][1] < sorted[j][1] }) // earliest deadline first
	taken := &maxHeap{} // chosen durations, longest on top
	day := 0
	for _, c := range sorted {
		heap.Push(taken, c[0])
		day += c[0]
		if day > c[1] { // past the deadline: drop the longest course taken so far
			day -= heap.Pop(taken).(int)
		}
	}
	return taken.Len()
}

Why it works

  1. Exchange argument: let o be the earliest-ending interval in an optimal answer and g the earliest-ending interval overall, the one greedy picks, so g.end ≤ o.end. Swapping o for g keeps the rest compatible, since they all start after o.end and hence after g.end, and the count is unchanged.
  2. Induction: after the swap, what is left is the same problem on the intervals that start after g.end, so the same argument applies to the rest.
  3. Sorting by start or by length both fail: with [1,10], [2,3], [4,5], start order keeps only one; with [1,5], [4,7], [6,10], taking the shortest [4,7] first also keeps only one, while two is possible in both.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
选最多的不重叠区间,我按结束时间排序,能放就放。理由是交换论证:最优解里结束最早的那个区间,总可以换成我选的这个结束更早的区间,后面的区间不受影响,数量不变。换完后剩下的是同样的问题,归纳下去就证明了贪心最优。排序 O(n log n),扫描 O(n);按开始时间或长度排序都有反例。
English
To keep the most non-overlapping intervals, I sort by end time and take each interval that fits. The exchange argument says the earliest-ending interval of any optimal answer can be swapped for mine, which ends no later, without breaking the rest or changing the count. What remains is the same problem, so induction shows greedy is optimal. Sorting costs O(n log n) and the scan O(n), and sorting by start or by length both have counterexamples.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. To pick the most pairwise non-overlapping intervals, the right greedy choice each step is the interval that:
  2. With coins {1, 3, 4} and amount 6, how many coins does "always take the largest coin that fits" use, and what is the minimum?
  3. "Can you reach the last index?" (a[i] is the longest jump from i): a greedy left-to-right scan keeps far, the farthest index reachable so far. When is the answer no?

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 25 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 2

#ProblemApproachRating
455Assign CookiesSort demands and resources, satisfying the smallest remaining demand with the smallest usable resource.
1338Reduce Array Size to The HalfRemove values in descending frequency order to minimize the number of types needed to halve the array.Rating 1303

Core 17

#ProblemApproachRating
55Jump GameMaintain the furthest reachable position and stop when the current position falls outside that range.
45Jump Game IICount jumps by advancing the boundary of the current reachable layer instead of choosing the largest local jump.
134Gas StationEliminate starting candidates using deficit intervals and also check whether the total fuel is sufficient.
135CandySatisfy left and right neighbor constraints separately, then combine each position's minimum requirements.
763Partition LabelsUse each character's last occurrence to identify partition boundaries that cannot be split further.Rating 1443
179Largest NumberDefine a sorting comparator through the two concatenation orders and handle an all-zero result.
1029Two City SchedulingStart from a common baseline cost and sort reassignment differences while meeting both cities' headcount constraints.Rating 1348
621Task SchedulerAnalyze the cooling gaps created by the most frequent tasks and compare the formula with heap simulation.
767Reorganize StringChoose the most frequent remaining character different from the previous one and check whether construction is possible.Rating 1681
1405Longest Happy StringChoose the highest remaining frequency without creating three equal consecutive characters, switching to the next choice when necessary.Rating 1821
881Boats to Save PeopleThe heaviest person needs a boat; test whether the lightest can join to justify the two-pointer strategy.Rating 1530
870Advantage ShuffleWin with the smallest sufficient value when possible; otherwise sacrifice the smallest value to preserve stronger ones.Rating 1648
948Bag of TokensBuy points at low energy cost and sell high-value tokens for energy, keeping track of the best score reached.Rating 1762
945Minimum Increment to Make Array UniqueAfter sorting, raise each value to at least one more than its predecessor and accumulate the minimum increments.Rating 1448
1007Minimum Domino Rotations For Equal RowTest only the two values on the first domino, then count the fewest rotations to align one side.Rating 1541
826Most Profit Assigning WorkSort workers by ability, scan feasible jobs, and maintain the highest available profit.Rating 1709
1642Furthest Building You Can ReachReserve limited ladders for the largest climbs, using a heap to revise resource assignments dynamically.Rating 1962

Advanced 6

#ProblemApproachRating
678Valid Parenthesis StringMaintain a range of possible unmatched-opening counts instead of enumerating the three meanings of every star.
630Course Schedule IIISchedule by deadline and remove the longest course when time runs out to preserve capacity for later courses.
871Minimum Number of Refueling StopsExtend the reachable range and, when fuel is insufficient, choose the largest supply from stations already passed.Rating 2074
502IPOUnlock projects by required capital, then choose the highest-profit project currently available.
857Minimum Cost to Hire K WorkersEnumerate the maximum wage-to-quality ratio and minimize the selected group's total quality to reduce cost.Rating 2260
1383Maximum Performance of a TeamScan by the minimum efficiency and maintain the speed sum of at most k workers to maximize performance.Rating 2091