1.8Problem-Solving Techniques
Covers IGNOU MCS-211 §1.7
Algorithm design techniques are general strategies that work for many different problems. Learning them is like learning chess openings: you do not memorise every game, but you recognise which plan fits the position. This page introduces the seven techniques that the rest of the course develops.
Brute force and exhaustive search
Brute force is simple, always applicable and often good enough for small inputs. Exhaustive search, however, becomes hopeless quickly. Guessing a 4-letter lowercase password by trying all strings needs up to attempts; each extra letter multiplies this by 26.
Divide and conquer
Divide and conquer solves a problem in three steps:
- Divide the instance into smaller instances of the same problem (often two halves).
- Conquer each smaller instance recursively; very small instances are solved directly.
- Combine the sub-solutions into a solution of the original instance.
It is a top-down approach. Examples: binary search, merge sort, quicksort, Strassen’s matrix multiplication, closest pair of points.
Greedy technique
A greedy algorithm builds a solution step by step, and at each step makes the choice that looks best right now (the locally optimal choice), never going back. It is used for optimisation problems: maximise or minimise an objective subject to constraints.
Greedy algorithms are fast and simple. For some problems they are provably optimal: Kruskal’s and Prim’s minimum spanning tree algorithms, Dijkstra’s shortest paths (with non-negative edge weights), Huffman coding and the fractional knapsack problem. For others they can fail.
# Make 6 rupees with as few coins as possible, coins are 1, 3 and 4.
coins = [4, 3, 1]
amount = 6
# Greedy: always take the largest coin that still fits.
greedy, left = [], amount
for c in coins:
while left >= c:
greedy.append(c)
left -= c
print("greedy :", greedy, "->", len(greedy), "coins")
# Dynamic programming: best[v] = fewest coins for value v.
INF = float("inf")
best = [0] + [INF] * amount
choice = [0] * (amount + 1)
for v in range(1, amount + 1):
for c in coins:
if c <= v and best[v - c] + 1 < best[v]:
best[v] = best[v - c] + 1
choice[v] = c
print("table :", best)
used, v = [], amount
while v > 0:
used.append(choice[v])
v -= choice[v]
print("optimal:", used, "->", len(used), "coins")greedy : [4, 1, 1] -> 3 coins
table : [0, 1, 2, 1, 1, 2, 2]
optimal: [3, 3] -> 2 coinsGreedy grabbed the 4 first and was then forced to use two 1s. The optimal answer, 3 + 3, starts with a coin that does not look best at the first step.
Dynamic programming
Dynamic programming (DP) solves a problem by combining solutions of smaller subproblems, like divide and conquer, but it is designed for the case where the subproblems overlap — the same subproblem appears again and again. DP solves each subproblem once and stores its answer in a table.
It can be written in two styles:
- Bottom-up (tabulation): fill the table from the smallest subproblems to the largest.
- Top-down (memoisation): write the natural recursion, but store each result the first time it is computed and look it up after that.
from functools import lru_cache
calls = 0
def fib_plain(n):
global calls
calls += 1
if n <= 1:
return n
return fib_plain(n - 1) + fib_plain(n - 2) # same subproblems solved again and again
memo_calls = 0
@lru_cache(maxsize=None)
def fib_memo(n):
global memo_calls
memo_calls += 1 # counts real computations only
if n <= 1:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
def fib_table(n): # bottom-up dynamic programming
f = [0, 1] + [0] * (n - 1)
for i in range(2, n + 1):
f[i] = f[i - 1] + f[i - 2]
return f[n]
n = 25
print("plain recursion:", fib_plain(n), "with", calls, "calls")
print("memoised :", fib_memo(n), "with", memo_calls, "computations")
print("bottom-up table:", fib_table(n))plain recursion: 75025 with 242785 calls
memoised : 75025 with 26 computations
bottom-up table: 75025Plain recursion recomputes small Fibonacci numbers hundreds of thousands of times; DP computes each of the 26 values once. Classic DP problems: 0/1 knapsack, subset sum, matrix-chain multiplication, Floyd–Warshall all-pairs shortest paths, Bellman–Ford single-source shortest paths, longest common subsequence.
Branch and bound
Branch and bound solves combinatorial optimisation problems by exploring a tree of partial solutions. The root stands for all solutions; each branch fixes one more choice. For each node it computes a bound — the best value any solution below that node could possibly reach. If the bound is no better than the best complete solution found so far, the whole subtree is pruned (skipped). Nodes can be explored breadth-first, depth-first or, most often, best-first (most promising bound first). The worst case is still exponential, but good bounds often make it fast in practice. It is used for 0/1 knapsack, TSP and job assignment.
Randomized algorithms
A randomized algorithm makes some of its choices using random numbers, for example choosing the pivot of quicksort at random, or choosing random candidate divisors when testing whether a large number is prime. Randomness protects against unlucky inputs and often gives simpler or faster algorithms. These are discussed further in the next section.
Backtracking
Backtracking builds a solution one component at a time, like a depth-first walk through a tree of choices. As soon as a partial solution cannot be completed into a valid one, it backtracks: it undoes the last choice and tries the next alternative. If no choices remain anywhere, there is no solution. Examples: the -queens puzzle, Sudoku, map colouring, subset sum. Backtracking is mainly used to find one or all solutions that satisfy constraints; branch and bound is its counterpart for optimisation.
Comparison of techniques
| Technique | Main idea | Optimal answer? | Typical cost | Examples |
|---|---|---|---|---|
| Brute force / exhaustive search | Try the direct way / try everything | Yes | Polynomial (brute force) to exponential (exhaustive) | Linear search; TSP by trying all tours |
| Divide and conquer | Split, solve recursively, combine | Yes | Often | Merge sort, binary search |
| Greedy | Best local choice, never undo | Only for some problems | Usually fast | Kruskal, Prim, Dijkstra, Huffman, fractional knapsack |
| Dynamic programming | Solve overlapping subproblems once, store in table | Yes | Polynomial in table size | 0/1 knapsack, Floyd–Warshall, LCS |
| Branch and bound | Tree search with bounds that prune | Yes | Exponential worst case, often fast | 0/1 knapsack, TSP, assignment |
| Randomized | Use random choices | Yes or with high probability | Good expected time | Randomized quicksort, primality tests |
| Backtracking | Depth-first build, undo dead ends | Yes (finds valid solutions) | Exponential worst case | n-queens, Sudoku, map colouring |
Key takeaways
- Brute force is the direct method; exhaustive search (try everything) is the exponential/factorial kind.
- Divide and conquer: divide, conquer recursively, combine.
- Greedy makes locally best choices; it is optimal only for some problems and needs a proof.
- Dynamic programming stores answers to overlapping subproblems (bottom-up or top-down).
- Branch and bound prunes with bounds; backtracking undoes dead ends; randomized algorithms use random choices.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain the three steps of divide and conquer and apply them to sort [5, 2, 4, 1] by merge sort.
Show worked answer
Divide: split the list into halves until single elements remain: [5, 2] and [4, 1] → [5], [2], [4], [1]. Conquer: single elements are sorted. Combine: merge [5] and [2] → [2, 5]; merge [4] and [1] → [1, 4]; merge [2, 5] and [1, 4]: 1, then 2, then 4, then 5 → [1, 2, 4, 5].