Greedy & Backtracking
- Prove a greedy algorithm correct with an exchange argument, or break it with a counterexample
- Solve interval problems by choosing the right sort key (start vs end) and boundary convention
- Write the backtracking template (choose, explore, unchoose) for subsets, combinations and permutations in Go
- Handle duplicates and prune the search tree, and state exponential complexity honestly
- Avoid the Go-specific backtracking bug: storing a slice that aliases the reused path
TL;DR
- Greedy makes the locally best choice and never revisits it. It is correct only if you can show an optimal solution exists that agrees with each greedy choice — the exchange argument.
- Intervals: sort by end to keep the maximum number of non-overlapping intervals; sort by start to merge or insert. Decide early whether touching endpoints overlap (prefer half-open
[start, end)). - Backtracking is DFS over a decision tree: choose → explore → unchoose. Subsets use a start index, permutations use a
usedset, combinations use a start index plus a size or sum target. - Duplicates: sort, then skip
nums[i] == nums[i−1]wheni > start(same value at the same depth). - Pruning is the whole performance story: sort and
breakwhen a candidate exceeds the remaining budget, track constraint sets (columns, diagonals), and bound the best achievable result. - Go gotcha:
out = append(out, path)stores a view of a buffer you keep mutating. Useslices.Clone(path).
When to reach for it
Greedy signals:
- "Maximum number of non-overlapping …", "minimum number of arrows/rooms/platforms", "minimum removals to make intervals disjoint".
- "Can you reach the end?", "minimum jumps", "assign cookies/tasks to maximize satisfied".
- A natural ordering exists (by deadline, end time, ratio) and you can argue that taking the extreme element first never hurts.
Backtracking signals:
- "Return all subsets / combinations / permutations / partitions / valid boards."
- Constraint satisfaction: N-Queens, Sudoku, word search on a grid, placing items under rules.
- Small n (roughly ≤ 10 for permutations, ≤ 20 for subsets) — the expected answer is exponential anyway.
- If the search revisits the same state many times and only a count or optimum is needed, it is DP in disguise — memoize (Dynamic Programming).
Core concepts
Why greedy works (when it does)
A greedy algorithm is correct when the problem has:
- Greedy-choice property: some optimal solution includes the greedy first choice.
- Optimal substructure: after making that choice, what remains is a smaller instance of the same problem.
Then induction finishes the proof. Two standard ways to argue property 1 (named in Kleinberg & Tardos' Algorithm Design):
- Exchange argument: take any optimal solution that differs from greedy's first choice, swap in the greedy choice, and show the result is still feasible and no worse.
- Greedy stays ahead: show that after every step, greedy's partial solution is at least as good as any other's by some measure.
Worked exchange argument — interval scheduling. Goal: keep the most pairwise non-overlapping intervals. Greedy: repeatedly keep the interval that ends earliest among those compatible with what you kept. Take an optimal solution O whose first interval is x, and let g be the earliest-ending interval overall. Since g ends no later than x, replacing x by g cannot create an overlap with O's remaining intervals (they all start after x ends, hence after g ends). The swapped solution has the same size, so an optimal solution starts with g; recurse on the intervals starting after g ends.
Breaking greedy. Always try a small counterexample before committing. Coin change with coins 1, 3, 4 and amount 6: largest-first gives three coins, optimal is two. 0/1 knapsack: best value-per-weight first fails with capacity 50 and items (weight 10, value 60), (20, 100), (30, 120) — the ratio-greedy picks the first two for 160; the optimum is the last two for 220. Fractional knapsack, where you may take part of an item, is greedy-optimal.
Greedy algorithms you already rely on: Dijkstra, Kruskal and Prim (Graphs), Huffman coding, earliest-deadline-first scheduling, and the "farthest reach" rule:
// canJump reports whether the last index is reachable (LeetCode 55):
// greedy stays ahead by tracking the farthest reachable index.
func canJump(nums []int) bool {
farthest := 0
for i, step := range nums {
if i > farthest {
return false // index i cannot be reached
}
farthest = max(farthest, i+step)
}
return true
}
Intervals
| Goal | Sort by | Rule |
|---|---|---|
| Merge overlapping intervals | start | Extend the last merged interval while the next starts before it ends |
| Max non-overlapping set / min removals | end | Keep an interval if it starts at or after the last kept end |
| Min arrows / min points hitting all intervals | end | Shoot at the first end; skip everything it hits |
| Min rooms / max concurrent | start (plus a heap) or a sweep over sorted events | Count active intervals (Heaps & Priority Queues) |
| Insert into a sorted, disjoint list | already sorted | Copy left part, merge the overlap, copy right part |
Fix the boundary convention first. Half-open [start, end) — a booking that checks out on the 5th does not overlap one that checks in on the 5th — matches how hotels, rate validity periods and maintenance windows work, and removes ±1 fiddling (Hotel Reservation System). Overlapping validity periods in a fee or FX table are a data bug: an interval sweep is the validation check you run before publishing the table.
The backtracking template
Backtracking explores a tree of partial solutions. At each node you choose an option, explore recursively, then unchoose to restore the state for the next option. Subsets of [1, 2, 3] with a start index — every node is one recorded subset:
// subsets returns every subset of nums (LeetCode 78).
func subsets(nums []int) [][]int {
var out [][]int
var path []int
var dfs func(start int)
dfs = func(start int) {
out = append(out, slices.Clone(path)) // copy: path's backing array is reused
for i := start; i < len(nums); i++ {
path = append(path, nums[i]) // choose
dfs(i + 1) // explore
path = path[:len(path)-1] // unchoose
}
}
dfs(0)
return out
}
The three shapes differ only in what the loop may pick next:
- Subsets / combinations: loop from
start; recurse withi + 1(each element once) ori(reuse allowed, as in Combination Sum). Combinations of size k stop whenlen(path) == k. - Permutations: loop over all indexes, skipping those in a
usedset; record whenlen(path) == n. - Partitions: choose the end of the next piece (
s[start:end]), check it is valid (e.g. a palindrome), recurse fromend.
// permute returns all orderings of distinct nums (LeetCode 46).
func permute(nums []int) [][]int {
var out [][]int
path := make([]int, 0, len(nums))
used := make([]bool, len(nums))
var dfs func()
dfs = func() {
if len(path) == len(nums) {
out = append(out, slices.Clone(path))
return
}
for i, v := range nums {
if used[i] {
continue
}
used[i] = true
path = append(path, v)
dfs()
path = path[:len(path)-1]
used[i] = false
}
}
dfs()
return out
}
Duplicates
With repeated values, sort first and skip a value that equals the previous one at the same depth (i > start), because choosing either copy there produces the same subtree:
// subsetsWithDup returns all distinct subsets (LeetCode 90).
func subsetsWithDup(nums []int) [][]int {
s := slices.Clone(nums)
slices.Sort(s)
var out [][]int
var path []int
var dfs func(start int)
dfs = func(start int) {
out = append(out, slices.Clone(path))
for i := start; i < len(s); i++ {
if i > start && s[i] == s[i-1] {
continue // same value at the same depth repeats a subtree
}
path = append(path, s[i])
dfs(i + 1)
path = path[:len(path)-1]
}
}
dfs(0)
return out
}
For permutations with duplicates (LeetCode 47) the rule becomes: skip s[i] if it equals s[i−1] and s[i−1] is not currently used.
Pruning and complexity
The output alone is exponential — subsets O(n·2ⁿ), permutations O(n·n!), k-combinations O(k·C(n, k)) — so pruning cannot beat the output size, but it can avoid exploring dead branches:
- Sort + break: if candidates are sorted and the current one exceeds the remaining budget, all later ones do too.
- Constraint sets: keep O(1) lookups for what is already taken (columns and diagonals in N-Queens, digits per row/column/box in Sudoku).
- Ordering heuristics: fill the most constrained position first (the Sudoku cell with the fewest candidates) to fail early.
- Bounding (branch and bound): in optimization searches, abandon a branch when even an optimistic estimate cannot beat the best solution found so far.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Greedy | Fast (often a sort + one pass), simple | Wrong without a proof | You can make an exchange or stays-ahead argument |
| Dynamic programming | Optimal for overlapping subproblems, polynomial or pseudo-polynomial | Needs a compact state; more memory | Optimum or count over choices that interact |
| Backtracking | Finds every solution, handles arbitrary constraints | Exponential | All solutions needed, or n is small |
| Branch and bound | Optimal with aggressive pruning | Worst case still exponential, bound design is hard | Small-to-medium optimization with good bounds |
| ILP / constraint solver | Declarative, handles complex rules at scale | External dependency, less predictable latency | Real scheduling/allocation problems in production |
In practice
Problem 1 — Non-overlapping Intervals (LeetCode 435)
Problem. Return the minimum number of intervals to remove so the rest do not overlap. Intervals that only touch ([1,2] and [2,3]) do not overlap.
Approach. Keeping the maximum number of compatible intervals minimizes removals. Sort by end; keep an interval if it starts at or after the last kept end (the exchange argument above proves it optimal).
func eraseOverlapIntervals(intervals [][2]int) int {
s := slices.Clone(intervals)
slices.SortFunc(s, func(a, b [2]int) int { return cmp.Compare(a[1], b[1]) }) // by end
removed := 0
end := math.MinInt
for _, iv := range s {
if iv[0] >= end {
end = iv[1] // keep: it ends earliest among the compatible intervals
} else {
removed++
}
}
return removed
}
Complexity. O(n log n) time, O(n) for the clone. Sorting by start instead is a common wrong answer: one long early interval would block many short ones.
Problem 2 — Merge Intervals (LeetCode 56)
Problem. Merge all overlapping intervals.
Approach. Sort by start; extend the last merged interval while the next one starts before it ends, otherwise start a new one.
func merge(intervals [][2]int) [][2]int {
if len(intervals) == 0 {
return nil
}
s := slices.Clone(intervals)
slices.SortFunc(s, func(a, b [2]int) int { return cmp.Compare(a[0], b[0]) })
out := [][2]int{s[0]}
for _, iv := range s[1:] {
last := &out[len(out)-1]
if iv[0] <= last[1] { // overlaps or touches the previous interval
last[1] = max(last[1], iv[1])
} else {
out = append(out, iv)
}
}
return out
}
Complexity. O(n log n) time, O(n) space. Change <= to < if touching intervals should stay separate — that is the boundary decision again. Operational uses: merging maintenance windows from several teams into a single blackout calendar, or coalescing a customer's card-block periods for a statement.
Problem 3 — Combination Sum (LeetCode 39)
Problem. Return all unique combinations of candidates (distinct, positive, reusable) that sum to the target.
Approach. Backtracking with a start index (so [2,3] and [3,2] are not both produced) and reuse allowed (dfs(i, …) rather than i + 1). Sorting enables the break prune.
func combinationSum(candidates []int, target int) [][]int {
c := slices.Clone(candidates)
slices.Sort(c) // enables the break below
var out [][]int
var path []int
var dfs func(start, remaining int)
dfs = func(start, remaining int) {
if remaining == 0 {
out = append(out, slices.Clone(path))
return
}
for i := start; i < len(c); i++ {
if c[i] > remaining {
break // sorted: every later candidate is too big too
}
path = append(path, c[i])
dfs(i, remaining-c[i]) // i, not i+1: reuse allowed
path = path[:len(path)-1]
}
}
dfs(0, target)
return out
}
Complexity. Exponential in target / min(candidate) in the worst case; the prune removes every branch that overshoots. Related shape in e-commerce: enumerating which gift cards or vouchers cover an amount exactly.
Problem 4 — N-Queens (LeetCode 51)
Problem. Place n queens on an n × n board so none attack each other; return all boards.
Approach. One queen per row, so recurse over rows and choose a column. Prune with O(1) checks: a column set, a / diagonal set indexed by r + c, and a \ diagonal set indexed by r − c + n − 1.
func solveNQueens(n int) [][]string {
var out [][]string
cols := make([]bool, n)
diag := make([]bool, 2*n-1) // r+c is constant on a "/" diagonal
anti := make([]bool, 2*n-1) // r-c+n-1 is constant on a "\" diagonal
queens := make([]int, n) // queens[r] = column of the queen in row r
var place func(r int)
place = func(r int) {
if r == n {
out = append(out, render(queens))
return
}
for c := range n {
if cols[c] || diag[r+c] || anti[r-c+n-1] {
continue // attacked square: prune
}
cols[c], diag[r+c], anti[r-c+n-1] = true, true, true
queens[r] = c
place(r + 1)
cols[c], diag[r+c], anti[r-c+n-1] = false, false, false
}
}
place(0)
return out
}
func render(queens []int) []string {
board := make([]string, len(queens))
row := make([]byte, len(queens))
for r, c := range queens {
for i := range row {
row[i] = '.'
}
row[c] = 'Q'
board[r] = string(row) // string() copies, so reusing row is safe
}
return board
}
Complexity. O(n!) upper bound, far less in practice thanks to pruning; O(n) state. Bitmasks instead of []bool make it several times faster and are a good follow-up.
Practice list
- Easy: Assign Cookies (455), Best Time to Buy and Sell Stock II (122), Lemonade Change (860)
- Medium: Jump Game (55), Jump Game II (45), Gas Station (134), Merge Intervals (56), Non-overlapping Intervals (435), Partition Labels (763), Subsets (78), Subsets II (90), Permutations (46), Combination Sum (39), Word Search (79), Palindrome Partitioning (131)
- Hard: N-Queens (51), Sudoku Solver (37), Candy (135)
Common pitfalls
- Greedy without proof. Passes the examples, fails hidden tests. Always try a two- or three-element counterexample.
- Wrong sort key for intervals (start when it should be end), or inconsistent treatment of touching endpoints.
- Aliasing the path:
out = append(out, path)stores a slice header pointing at the buffer you keep modifying, so every stored result changes later. Symptom: all results look identical or are garbled. Alwaysslices.Clone(path)(Common Pitfalls). - Forgetting to unchoose (
used[i] = false, removing the queen) — later branches see stale state. - Duplicate results from skipping with
i > 0instead ofi > start(which also drops valid combinations), or from not sorting first. - No pruning — the solution is correct but times out at n = 12.
- Recursive closures in Go:
dfs := func…cannot call itself; declarevar dfs func(int)first, then assign.
Interview angle
- For greedy, interviewers want the argument, not just code: "sorting by end is optimal because swapping any first interval for the earliest-ending one keeps the solution feasible and the same size". Two sentences are enough.
- For backtracking, draw the decision tree for a tiny input, state the template, then name your pruning. Give the honest complexity (exponential) and the output size.
- Expected follow-ups: handle duplicates, return only the count (often DP), stop at the first solution, parallelize the search (split top-level branches across goroutines with a shared result channel and cancellation via
context). - Architect angle: production scheduling and allocation (delivery slots, settlement batch windows, seat or room assignment) are usually greedy heuristics or solver-backed, with exhaustive search reserved for tiny, bounded cases. Say where you would draw that line and how you would keep results explainable to customers and auditors.
- Red flags: claiming greedy works "intuitively", or exponential code with no awareness of its growth.
Self-check
1. Give the exchange argument for "sort intervals by end time" in maximum interval scheduling.
Let g be the interval that ends first and O an optimal solution whose first interval is x. Since g ends no later than x, every other interval in O (which starts after x ends) also starts after g ends. Replacing x with g keeps O feasible and the same size, so some optimal solution starts with g. The remaining problem — intervals starting after g ends — has the same structure, so induction completes the proof.
2. Why does largest-coin-first fail for coins 1, 3, 4 but work for typical currency denominations?
For 6, greedy takes 4 then 1 + 1 (three coins) while 3 + 3 uses two; taking the largest coin does not preserve an optimal remainder. Typical currencies are "canonical" systems, designed so greedy is optimal with unlimited supply. With limited notes (an ATM cassette) greedy can still fail, which makes it a bounded knapsack.
3. What changes between the subsets, combinations and permutations templates?
Subsets record every node and loop from start, recursing with i + 1. Combinations also loop from start but record only when a size k or a sum target is reached (and recurse with i if reuse is allowed). Permutations loop over all indexes, skip used ones with a used set, and record when the path length is n.
4. Why must you skip duplicates with i > start rather than i > 0?
The goal is to avoid choosing the same value twice at the same depth, which creates identical subtrees. i > start skips a repeat only among siblings at the current level. i > 0 would also skip using the second copy of a value deeper in the tree (as the next element after the first copy), losing valid results such as [2, 2].
5. In Go, why is out = append(out, path) a bug in backtracking?
path is a slice header pointing at a backing array that the search keeps modifying (appending and truncating). Storing the header stores a view, not a snapshot, so every saved result changes as the search continues and later ones overwrite earlier ones. slices.Clone(path) (or append([]int(nil), path...)) stores an independent copy.
6. Scenario: the operations team gives you 40 nightly batch jobs, each with an allowed time window, and asks you to run as many as possible on one exclusive database maintenance slot. What do you do?
If each job occupies its whole window, it is maximum interval scheduling: sort by end time and greedily keep compatible jobs — optimal and O(n log n). If jobs have durations shorter than their windows and you choose start times, it becomes a scheduling problem with release times and deadlines that is harder in general; use earliest-deadline-first heuristics or a solver. Make the boundary convention explicit and report which jobs were dropped and why.
Exercise
Write a validity package for time-bounded reference data (fee schedules, FX margins), using half-open [from, to) periods:
Overlaps(periods)returns every pair of overlapping periods (sort by start, sweep) — the pre-publication data check.Merge(periods)andGaps(periods, from, to)(uncovered sub-periods inside a range).BestVouchers(vouchers, basket, maxStack)— backtracking over voucher combinations with a branch-and-bound prune (stop a branch when the remaining vouchers' maximum possible discount cannot beat the best so far). Compare against a greedy "largest discount first" and find an input where greedy loses.
Done when table-driven tests cover touching endpoints, nested periods, empty input and the greedy counterexample, and the search explores measurably fewer nodes with the prune than without (count them).
Further reading
- Jon Kleinberg & Éva Tardos, Algorithm Design — greedy algorithms chapter (exchange arguments, "greedy stays ahead")
- Introduction to Algorithms (CLRS) — greedy algorithms chapter (activity selection, Huffman codes)
- Steven Skiena, The Algorithm Design Manual — combinatorial search and backtracking chapter
- Donald Knuth, "Dancing Links" (2000) — exact-cover backtracking (Sudoku, tiling)
- Peter Norvig, "Solving Every Sudoku Puzzle" — constraint propagation plus search, in a short essay
Related
- Dynamic Programming — when greedy fails and the search has overlapping states.
- Heaps & Priority Queues — meeting rooms and interval scheduling with a heap.
- Graphs — greedy graph algorithms (Dijkstra, Kruskal) and DFS.
- Hotel Reservation System — interval logic for bookings.
- Pricing & Promotions — combining vouchers and discounts.
- Common Pitfalls — slice aliasing in Go.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).