Information Technology is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Algorithms and design strategies

Algorithms and design strategies survey major methods (brute force, divide-and-conquer, greedy, dynamic programming, backtracking, branch-and-bound, randomized and approximation) with exact definitions, Master Theorem, recurrence solving, patterns, worked examples and C++ code for memoized vs naive

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Two or three sentences: Engineers use algorithm design strategies to choose a method that gives correct results within time and memory limits. Knowing which strategy (for example divide-and-conquer, greedy, or dynamic programming) fits a problem guides both correct solutions and efficient implementations used in systems, compilers, databases, routing, and optimization tasks.

Key ideas

  • Divide-and-conquer — split a problem into independent subproblems, solve each recursively, and combine their solutions. Requirements: subproblems are smaller, often identical in structure, and combining step is efficient. Formal recurrence: if T(n) is time, T(n) = a·T(n/b) + f(n). Draw a recursion tree: root cost f(n), a children each cost f(n/b), etc., label levels and leaves.

  • Greedy method — make the best local choice at each step hoping to reach a global optimum. Two required properties for correctness: optimal substructure (optimal solution contains optimal solutions to subproblems) and the greedy-choice property (a locally optimal choice can be extended to an optimal global solution). Define both: optimal substructure means for problem P of size n with optimal solution S, every sub-solution of S is optimal for the corresponding subproblem. Greedy-choice property: there exists an optimal solution that begins with a greedy choice.

  • Dynamic programming (DP) — use when problem has optimal substructure and overlapping subproblems (same subproblem solved many times). Two styles: top-down memoization (recursive with cache) and bottom-up tabulation (build table iteratively). Define overlapping subproblems: the recursion tree has repeated identical subproblems.

  • Backtracking — depth-first search through solution space with pruning when partial solution cannot lead to a full solution. Useful for constraint satisfaction (e.g., N-Queens). Define pruning: cutting branches that cannot produce a feasible or better solution.

  • Branch-and-bound — search with bounds on best possible solution in a branch to prune branches that cannot beat current best; used in optimization (e.g., 0/1 knapsack exact solutions, travelling salesman exact). Define bound: an upper or lower estimate of the best possible solution in that subtree.

  • Randomized algorithms — use random choices during execution; classify into Las Vegas (always correct, time randomized) and Monte Carlo (time bounded (e.g., polynomial), correctness probabilistic). Define both.

  • Approximation algorithms — polynomial-time algorithms that return near-optimal solutions with provable approximation ratio r (define ratio: for minimization, algorithm output A satisfies A/OPT ≤ r). For maximization, OPT/A ≤ r, and typically r ≥ 1; the bound is a worst-case guarantee.

  • Master Theorem (statement, exact): For recurrence T(n)=a·T(n/b)+f(n) with constants a ≥ 1 and b > 1 and f(n) positive, compare f(n) with n^{log_b a}.

    • If f(n) = O(n^{c}) where c < log_b a, then T(n) = Θ(n^{log_b a}).
    • If f(n) = Θ(n^{log_b a}·log^k n) for k ≥ 0, then T(n) = Θ(n^{log_b a}·log^{k+1} n).
    • If f(n) = Ω(n^{c}) where c > log_b a, and if a·f(n/b) ≤ c'·f(n) for some c' < 1 and sufficiently large n (regularity), then T(n) = Θ(f(n)). State assumptions: a and b constants, f(n) asymptotically positive, and regularity condition for case 3.
  • Common derivation universities ask: derive merge sort cost using recurrence T(n)=2T(n/2)+Θ(n). Show recursion tree levels: level i has 2^i nodes each cost Θ(n/2^i) so total per level Θ(n); number of levels log_2 n; total Θ(n log n). Describe exactly what to draw: a binary tree with root labelled Θ(n), then two children Θ(n/2), then four Θ(n/4) to leaves Θ(1); count levels and sum.

Formulas

T(n) = a·T(n/b) + f(n) — recurrence for divide-and-conquer; a = number of subproblems, b = factor by which size reduces, f(n) = combine cost; time unit: steps; use Master Theorem to solve when a and b are constants.

n^{log_b a} — critical function in Master Theorem; log base b of a.

If f(n) = Θ(n^{log_b a}) then T(n) = Θ(n^{log_b a}·log n) — meaning k = 0 case.

Syntax patterns to remember (C++ style): // top-down memoization pattern int solve(int x) { if (memo[x]!=-1) return memo[x]; memo[x]=...; return memo[x]; }

// bottom-up DP pattern for (int i=base;i<=N;i++) table[i] = combine(table[prev states]);

// greedy loop pattern sort(items, comparator); for(item : items) if (feasible(item)) take(item);

// backtracking pattern void dfs(state) { if (isGoal) record; for(option : options) { if (promising(option)) { apply(option); dfs(state'); undo(option); } } }

Worked examples

  1. Derive time for merge sort (exam style):

    • Problem: merge sort on n elements.
    • Recurrence: T(n) = 2·T(n/2) + cn where c is constant for merging.
    • By Master Theorem: a=2, b=2 so n^{log_b a} = n^{log_2 2} = n.
    • f(n)=cn = Θ(n^{log_b a}) so this is case 2 with k=0, therefore T(n)=Θ(n log n).
    • Diagram to draw: recursion tree of 2-ary splits: root Θ(n), next level 2 nodes Θ(n/2), ... total per level Θ(n), number of levels log_2 n → total Θ(n log n). Bold final: T(n) = Θ(n log n).
  2. C++ example: naive Fibonacci (exponential) vs DP memoized (linear). Provide complete programs, sample I/O and exact outputs.

Naive Fibonacci (recursive):

#include <bits/stdc++.h>
using namespace std;
long long fib_naive(int n) {
    if (n<=1) return n;
    return fib_naive(n-1) + fib_naive(n-2);
}
int main() {
    int n; if (!(cin>>n)) return 0;
    cout<<fib_naive(n)<<"\n";
    return 0;
}

Sample input: 10 Exact output: 55

Memoized Fibonacci (top-down DP):

#include <bits/stdc++.h>
using namespace std;
vector<long long> memo;
long long fib_memo(int n) {
    if (n<=1) return n;
    if (memo[n] != -1) return memo[n];
    return memo[n] = fib_memo(n-1) + fib_memo(n-2);
}
int main(){
    int n; if(!(cin>>n)) return 0;
    memo.assign(n+1, -1);
    cout<<fib_memo(n)<<"\n";
    return 0;
}

Sample input: 40 Exact output: 102334155

Notes: naive version is Θ(φ^n) time (φ ~ 1.618), memoized is Θ(n) time and Θ(n) space.

  1. Model answer (theory question): Explain when greedy fails and DP is needed (short note):
    • Give counterexample: Fractional knapsack vs 0/1 knapsack. Fractional allows splitting items and greedy by value/weight works (proof sketch: exchange argument). For 0/1 knapsack greedy by ratio fails — give small numbers: capacity 50, items: (value=60,w=10),(value=100,w=20),(value=120,w=30). Greedy by ratio would take 60/10=6 first, then next 100/20=5, but best is items with weights 20+30=50 value 220; greedy might pick wrong. Conclude DP (0/1 knapsack) uses table with states (i, w) and is Θ(n·W) time.

Common mistakes

  • For memoization, forgetting to initialize memo table or using wrong base cases causing wrong answers or segmentation faults.
  • In greedy proofs, giving intuitive reason but not providing an exchange or cut-and-paste proof showing local choice can be extended to optimal.
  • Mixing up Las Vegas and Monte Carlo definitions (Las Vegas: correct result, random time; Monte Carlo: fixed time, probabilistic correctness).

For your exam

Kinds of questions: definitions, short notes, derivations (e.g., derive recurrence solutions), proof obligations (show greedy correctness or counterexample), complexity numericals, program writing (memoization or greedy implementation), and diagram-based answers (recursion tree). Full-marks answers include: clear definition (bold term), assumptions, step-by-step derivation (show recurrence and how you solved it, draw recursion tree if asked), and final Theta/Big-O statement. For proof-type answers, include formal proof style (exchange argument for greedy, induction for DP correctness, or verification of Master Theorem case used).

Quick check

  1. Define greedy-choice property in one sentence.
  2. Solve T(n)=3T(n/3)+n using Master Theorem — state Θ(...) result.
  3. Name two differences between top-down memoization and bottom-up DP. Answers: 1) A locally optimal choice that can be extended to a global optimum. 2) a=3, b=3 ⇒ n^{log_b a}=n^{1}=n and f(n)=n so case 2 ⇒ Θ(n log n). 3) Top-down uses recursion+cache and may compute only needed states; bottom-up fills table iteratively and avoids recursion overhead.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?