A brute-force (exhaustive search) algorithm systematically tries every possible solution until it finds one that is correct (or determines no solution exists).
ALGORITHM LongestPath(graph, start, end)
// Generate all possible paths, return the longest
allPaths ← GenerateAllPaths(graph, start, end)
return max(length(p) for p in allPaths)
For a graph with $n$ nodes, there could be up to $n!$ paths — factorial growth.
For a problem with $n$ elements:
- Permutations: $O(n!)$
- Subsets: $O(2^n)$
- Pairs: $O(n^2)$
KEY TAKEAWAY: Brute-force guarantees correctness but is only feasible for small inputs. For large inputs, exponential/factorial complexity makes it impractical — this motivates better design patterns.
A greedy algorithm makes a sequence of choices, each time selecting the locally optimal (best-looking) option at that moment, without reconsidering previous choices.
A globally optimal solution can be reached by making locally optimal choices. This must be proven for greedy to be applicable.
| Algorithm | Greedy Choice | Global Optimal? |
|---|---|---|
| Prim’s (MST) | Always add the cheapest available edge | Yes |
| Dijkstra’s | Always relax the closest unvisited vertex | Yes (non-negative weights) |
| Coin change (certain systems) | Always use the largest denomination first | Not always |
ALGORITHM Prim(graph, start)
mst ← {}
visited ← {start}
while visited ≠ all vertices do
edge ← cheapest edge from visited to unvisited vertex
add edge to mst
add new vertex to visited
end while
return mst
Each step adds the minimum-weight edge that expands the MST — a greedy choice.
| Property | Brute-Force | Greedy |
|---|---|---|
| Strategy | Try all options | Make best local choice |
| Optimality | Always optimal | Optimal for some problems |
| Complexity | Exponential / factorial | Usually polynomial |
| Backtracking | Yes (tries all) | No |
| Difficulty | Simple to implement | Requires proof of correctness |
| Suitable for | Small inputs, NP-Hard problems | MST, shortest path, scheduling |
EXAM TIP: When asked to compare brute-force and greedy, address: (1) strategy, (2) optimality guarantee, (3) computational complexity, and (4) suitability for the given problem.
COMMON MISTAKE: Greedy is NOT always optimal. Always check whether the problem has the greedy choice property before applying it. A classic counterexample is the coin-change problem with non-standard denominations.