Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Algorithm design patterns
EXPERIMENT 51 / 66

Take the best next step—with a reason.

Know when a local choice has a global correctness argument.

BY NAVAN SAMI◷ 8 MIN READSTRETCHALGORITHM

01 Model the idea

A greedy algorithm commits to a local choice without revisiting it. That is a design pattern, not proof of optimality. For maximising the number of nonoverlapping positive-duration intervals, choosing the earliest finishing compatible interval has an exchange argument: replacing an optimal solution’s first interval with the earliest finisher leaves at least as much room for the rest. Other objectives, such as weighted value, need a different argument or algorithm.

THE THING THAT MUST STAY TRUE

The chosen set stays feasible and leaves maximum remaining time after each greedy choice.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
SORT by increasing finish time
ACCEPT each interval compatible with the last accepted end

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

greedy.py
def select_intervals(intervals):
    chosen, end = [], float("-inf")
    for name, start, finish in sorted(intervals, key=lambda item: item[2]):
        if start >= finish: raise ValueError("Positive-duration intervals required")
        if start >= end:
            chosen.append(name); end = finish
    return chosen
print(select_intervals([("long", 0, 10), ("A", 0, 2), ("B", 2, 4), ("C", 4, 6)]))
↳ EXPECTED OUTPUT
['A', 'B', 'C']
  1. 1

    The sort makes the local rule explicit. A half-open interval may begin exactly when the previous interval finishes.

  2. 2

    The objective is number of accepted intervals, not total duration or revenue. Changing the objective can invalidate the same greedy rule.

  3. 3

    Look for an exchange argument or another proof before relying on a plausible heuristic. A counterexample is often easier to find than a full proof, so test small adversarial cases.

04 Count the cost

TIME

O(n log n) sorting plus O(n) scan

SPACE

O(n) sorted input copy and result

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Give a counterexample to selecting the earliest-starting interval first.

Reveal one possible solution +
one_possible_solution.py
intervals = [("long", 0, 10), ("A", 1, 2), ("B", 2, 3)]
earliest_start_count = 1
earliest_finish_count = 2
assert earliest_finish_count > earliest_start_count
print("A then B beats long")

06 Check your reasoning

QUICK SIGNAL CHECK

What makes a greedy rule trustworthy?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.