MCS-211 · Block 1 Unit 1

Basics of an Algorithm and its Properties

Section 8 of 9

Block 1 · Unit 1Basics of an Algorithm and its Properties16 min · Section 8 of 9

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 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 264=456,97626^4 = 456{,}976 attempts; each extra letter multiplies this by 26.

Divide and conquer

Divide and conquer solves a problem in three steps:

  1. Divide the instance into smaller instances of the same problem (often two halves).
  2. Conquer each smaller instance recursively; very small instances are solved directly.
  3. 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.

Dividesplit into smaller instances
→
Conquersolve each one recursively
→
Combinemerge the sub-solutions
Divide and conquer

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.

Python · greedy_coins.py
# 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")
Output
greedy : [4, 1, 1] -> 3 coins
table  : [0, 1, 2, 1, 1, 2, 2]
optimal: [3, 3] -> 2 coins

Greedy 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.
Python · fib_calls.py
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))
Output
plain recursion: 75025 with 242785 calls
memoised       : 75025 with 26 computations
bottom-up table: 75025

Plain recursion recomputes small Fibonacci numbers hundreds of thousands of times; DP computes each of the 26 values F(0),…,F(25)F(0), \dots, F(25) 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 nn-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

TechniqueMain ideaOptimal answer?Typical costExamples
Brute force / exhaustive searchTry the direct way / try everythingYesPolynomial (brute force) to exponential (exhaustive)Linear search; TSP by trying all tours
Divide and conquerSplit, solve recursively, combineYesOften O(nlog⁡n)O(n \log n)Merge sort, binary search
GreedyBest local choice, never undoOnly for some problemsUsually fastKruskal, Prim, Dijkstra, Huffman, fractional knapsack
Dynamic programmingSolve overlapping subproblems once, store in tableYesPolynomial in table size0/1 knapsack, Floyd–Warshall, LCS
Branch and boundTree search with bounds that pruneYesExponential worst case, often fast0/1 knapsack, TSP, assignment
RandomizedUse random choicesYes or with high probabilityGood expected timeRandomized quicksort, primality tests
BacktrackingDepth-first build, undo dead endsYes (finds valid solutions)Exponential worst casen-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 1 · multiple choice

Which technique fits a problem whose recursive solution solves the same subproblems many times?

Show answer

Answer: C. Dynamic programming

Overlapping subproblems are exactly what DP’s table removes. Divide and conquer is best when subproblems are independent.

Question 2 · multiple choice

With coins {1, 3, 4}, how many coins does the greedy method use to make 6?

Show answer

Answer: B. 3

Greedy takes 4, then 1, then 1: three coins. The optimum is 3 + 3, two coins, which shows greedy is not always optimal.

Question 3 · multiple choice

Which algorithm solves the single-source shortest path problem using dynamic programming?

Show answer

Answer: D. Bellman–Ford

Bellman–Ford is single-source and DP-based. Floyd–Warshall is DP but all-pairs; Kruskal and Prim are greedy MST algorithms.

Question 4 · multiple choice

Plain recursion computes Fibonacci F(25) with 242,785 calls. How many distinct values does bottom-up DP compute?

Show answer

Answer: A. 26

DP computes F(0), F(1), …, F(25) once each: 26 values. The large number is caused by repeated subproblems.

Question 5 · multiple choice

Which statement about brute force is correct?

Show answer

Answer: C. Linear search and selection sort are brute-force algorithms.

Brute force is the direct approach; many such algorithms are polynomial. Only exhaustive search over subsets or permutations is exponential or factorial.

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].

↑ ↓ move↵ openTab switch type