Skip to main content

Chapter 2

Design and Analysis of Algorithms

TU BSc CSIT past exam questions

Past questions and answers

68 questions set from this chapter. Most repeated first.

  • 2076 · 10 marks

Explain the divide and conquer paradigm from algorithm design with a suitable example. Write the Quick sort algorithm using a randomized approach and explain its time complexity.

Similar questions: Explain about the divide and conquer paradigm for algorithm (2078)

Answer

Divide and conquer

Divide and conquer solves a problem in three steps:

  1. Divide the problem into smaller sub-problems of the same type.
  2. Conquer the sub-problems by solving them recursively (solve directly when small enough, the base case).
  3. Combine the solutions of the sub-problems into the solution of the original problem.

Its running time satisfies a recurrence T(n)=a T(n/b)+f(n)T(n) = a\,T(n/b) + f(n), solved by the master theorem. Examples: merge sort, quick sort, binary search, Strassen's matrix multiplication.

Example: merge sort. Divide the array into two halves, sort each recursively, and merge the two sorted halves in linear time. Thus T(n)=2T(n/2)+Θ(n)⇒T(n)=Θ(nlog⁡n).T(n) = 2T(n/2) + \Theta(n) \Rightarrow T(n) = \Theta(n \log n).

Randomized quick sort

Ordinary quick sort picks a fixed pivot (e.g. the last element) and is O(n2)O(n^2) for already sorted input. Randomized quick sort chooses the pivot at random, so no particular input is bad.

RANDOMIZED-QUICKSORT(A, p, r)
    if p < r
        q = RANDOMIZED-PARTITION(A, p, r)
        RANDOMIZED-QUICKSORT(A, p, q - 1)
        RANDOMIZED-QUICKSORT(A, q + 1, r)

RANDOMIZED-PARTITION(A, p, r)
    i = RANDOM(p, r)            // random index in [p, r]
    exchange A[r] with A[i]
    return PARTITION(A, p, r)

PARTITION(A, p, r)
    x = A[r]                    // pivot
    i = p - 1
    for j = p to r - 1
        if A[j] <= x
            i = i + 1
            exchange A[i] with A[j]
    exchange A[i + 1] with A[r]
    return i + 1

Time complexity

PARTITION takes Θ(n)\Theta(n) time for nn elements.

  • Worst case (pivot is always the smallest or largest): T(n)=T(n−1)+Θ(n)T(n) = T(n-1) + \Theta(n), so T(n)=Θ(n2)T(n) = \Theta(n^2). With random pivots this occurs with a very small probability.
  • Best case (pivot splits into two equal halves): T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n).
  • Expected case: every pivot rank is equally likely, so E[T(n)]=1n∑q=0n−1(E[T(q)]+E[T(n−1−q)])+Θ(n)=2n∑q=0n−1E[T(q)]+Θ(n),E[T(n)] = \frac{1}{n}\sum_{q=0}^{n-1}\big(E[T(q)] + E[T(n-1-q)]\big) + \Theta(n) = \frac{2}{n}\sum_{q=0}^{n-1}E[T(q)] + \Theta(n), which solves to E[T(n)]=O(nlog⁡n)E[T(n)] = O(n \log n). Even a 9:1 split every time gives T(n)=T(9n/10)+T(n/10)+cn=O(nlog⁡n)T(n) = T(9n/10) + T(n/10) + cn = O(n\log n).

So the expected running time is O(nlog⁡n)O(n \log n) for every input, the worst case is O(n2)O(n^2), and the space used is O(log⁡n)O(\log n) expected for the recursion stack.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 10 marks

Explain about the divide and conquer paradigm for algorithm design with suitable example. Write the Quick sort algorithm using randomized approach and explain its time complexity.

Similar questions: Explain the divide and conquer paradigm from algorithm desig (2076)

Answer

Divide and conquer

This paradigm solves a problem in three steps.

  1. Divide: split the problem into smaller subproblems of the same kind.
  2. Conquer: solve the subproblems recursively. A small enough subproblem is solved directly (the base case).
  3. Combine: merge the subproblem solutions into the solution of the original problem.

The running time is given by a recurrence T(n)=aT(n/b)+D(n)+C(n)T(n)=aT(n/b)+D(n)+C(n), where D(n)D(n) and C(n)C(n) are the divide and combine costs.

Example: merge sort. Divide the array into two halves. Sort each half recursively. Merge the two sorted halves in O(n)O(n) time. The recurrence is T(n)=2T(n/2)+Θ(n)T(n)=2T(n/2)+\Theta(n), which gives T(n)=Θ(nlog⁡n)T(n)=\Theta(n\log n). Other examples are binary search, quick sort and Strassen's matrix multiplication.

Randomized quick sort

Plain quick sort has O(n2)O(n^2) worst-case behaviour on already sorted input if the first or last element is the pivot. Randomized quick sort picks the pivot at random, so that no particular input is always bad.

RANDOMIZED-QUICKSORT(A, p, r)
1  if p < r
2      q = RANDOMIZED-PARTITION(A, p, r)
3      RANDOMIZED-QUICKSORT(A, p, q-1)
4      RANDOMIZED-QUICKSORT(A, q+1, r)

RANDOMIZED-PARTITION(A, p, r)
1  i = RANDOM(p, r)
2  swap A[r], A[i]
3  return PARTITION(A, p, r)

PARTITION(A, p, r)
1  x = A[r]; i = p - 1
2  for j = p to r-1
3      if A[j] <= x
4          i = i + 1; swap A[i], A[j]
5  swap A[i+1], A[r]
6  return i + 1

Time complexity

  • Partition takes Θ(n)\Theta(n) time.
  • Worst case: the pivot is always the smallest or largest element, so T(n)=T(n−1)+Θ(n)=Θ(n2)T(n)=T(n-1)+\Theta(n)=\Theta(n^2). With random pivots this has probability very small.
  • Best case: balanced splits, T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n)T(n)=2T(n/2)+\Theta(n)=\Theta(n\log n).
  • Expected case: for any input, the expected running time is O(nlog⁡n)O(n\log n). The expected number of comparisons is at most 2nln⁡n≈1.39 nlog⁡2n2n\ln n\approx1.39\,n\log_2 n. The reason is that two elements zi<zjz_i<z_j are compared only if one of them is the first pivot chosen among zi,…,zjz_i,\dots,z_j, which has probability 2/(j−i+1)2/(j-i+1). Summing over all pairs gives E[X]=∑i<j2j−i+1=O(nlog⁡n)E[X]=\sum_{i<j}\frac{2}{j-i+1}=O(n\log n)

Even a split such as 9:1 each time gives O(nlog⁡n)O(n\log n), which is why the average case is so good.

Space: O(log⁡n)O(\log n) expected for the recursion stack.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain the recursion tree method for solving the recurrence relation. Solve following recurrence relation using this method.
T(n)=2T(n/2) +1 for n> 1, T(n) =1 for n =1

Similar questions: Solve the recurrence relation T(n) = 2T(n/2) + n using recur (2082)

Answer

Recursion tree method

The recurrence is drawn as a tree. The root is the cost of the top-level call (the non-recursive work f(n)f(n)). Each node has one child for every recursive call, labelled with the cost of that smaller call. Every level is summed, and the level sums are added to get the total. The result is used as a guess and can be confirmed by substitution.

Solving T(n)=2T(n/2)+1T(n)=2T(n/2)+1, with T(1)=1T(1)=1

  • Level 0 has 1 node of cost 1, so the sum is 1.
  • Level 1 has 2 nodes of cost 1 each, so the sum is 2.
  • Level 2 has 4 nodes of cost 1 each, so the sum is 4.
  • Level ii has 2i2^i nodes of cost 1 each, so the sum is 2i2^i.

The subproblem size at level ii is n/2in/2^i. It reaches 1 at i=log⁡2ni=\log_2 n. The last level has 2log⁡2n=n2^{\log_2 n}=n leaves, each costing T(1)=1T(1)=1.

T(n)=∑i=0log⁡2n−12i+n=(n−1)+n=2n−1T(n)=\sum_{i=0}^{\log_2 n-1}2^i+n=(n-1)+n=2n-1

So T(n)=Θ(n)T(n)=\Theta(n).

Check by substitution. Assume T(n)=2n−1T(n)=2n-1. Then 2T(n/2)+1=2(n−1)+1=2n−12T(n/2)+1=2(n-1)+1=2n-1, which equals T(n)T(n), and T(1)=1T(1)=1 holds.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Solve the following linear congrvences using Chinese Remainder Theorem.
X=l (MOD 2)
X=3 (MOD 5)
x=6 (MOD 7)

Similar questions: Solve the following linear equation using Chinese Remainder (2081)

Answer

We solve x≡1(mod2)x\equiv1 \pmod 2, x≡3(mod5)x\equiv3\pmod 5, x≡6(mod7)x\equiv6\pmod 7.

The moduli 2, 5, 7 are pairwise coprime, so CRT applies with

M=2⋅5⋅7=70,M1=702=35,M2=705=14,M3=707=10.M=2\cdot5\cdot7=70,\quad M_1=\frac{70}{2}=35,\quad M_2=\frac{70}{5}=14,\quad M_3=\frac{70}{7}=10.

Find the inverses yiy_i with Miyi≡1(modmi)M_iy_i\equiv1\pmod{m_i}:

  • 35y1≡1(mod2)35y_1\equiv1\pmod 2: 35≡135\equiv1, so y1=1y_1=1.
  • 14y2≡1(mod5)14y_2\equiv1\pmod 5: 14≡414\equiv4, and 4⋅4=16≡14\cdot4=16\equiv1, so y2=4y_2=4.
  • 10y3≡1(mod7)10y_3\equiv1\pmod 7: 10≡310\equiv3, and 3⋅5=15≡13\cdot5=15\equiv1, so y3=5y_3=5.

Now

x=∑aiMiyi=1⋅35⋅1+3⋅14⋅4+6⋅10⋅5=35+168+300=503.x=\sum a_iM_iy_i=1\cdot35\cdot1+3\cdot14\cdot4+6\cdot10\cdot5=35+168+300=503.

x≡503(mod70)⇒503−7⋅70=503−490=13.x\equiv503 \pmod{70}\Rightarrow 503-7\cdot70=503-490=13.

x≡13(mod70)x\equiv13\pmod{70}.

Check: 13 mod 2=113 \bmod 2=1, 13 mod 5=313\bmod5=3, 13 mod 7=613\bmod7=6. All three hold.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Solve the following linear equation using Chinese Remainder Theorem.
x = 1 MOD 3
x = 2 MOD 5
x = 0 MOD 7

Similar questions: Solve the following linear congrvences using Chinese Remaind (2079)

Answer

Chinese Remainder Theorem

We solve x≡1(mod3)x \equiv 1 \pmod 3, x≡2(mod5)x \equiv 2 \pmod 5, x≡0(mod7)x \equiv 0 \pmod 7. The moduli 3, 5, 7 are pairwise coprime, so a unique solution exists modulo

M=3×5×7=105.M = 3 \times 5 \times 7 = 105.

Compute Mi=M/miM_i = M/m_i and the inverse yiy_i of MiM_i modulo mim_i:

  • m1=3m_1=3: M1=35M_1 = 35, 35≡2(mod3)35 \equiv 2 \pmod 3, and 2y1≡1(mod3)2y_1 \equiv 1 \pmod 3 gives y1=2y_1 = 2.
  • m2=5m_2=5: M2=21M_2 = 21, 21≡1(mod5)21 \equiv 1 \pmod 5, so y2=1y_2 = 1.
  • m3=7m_3=7: M3=15M_3 = 15, 15≡1(mod7)15 \equiv 1 \pmod 7, so y3=1y_3 = 1.

x=∑aiMiyi=1⋅35⋅2+2⋅21⋅1+0⋅15⋅1=70+42=112.x = \sum a_i M_i y_i = 1\cdot 35\cdot 2 + 2\cdot 21\cdot 1 + 0\cdot 15\cdot 1 = 70 + 42 = 112.

x≡112(mod105)≡7.x \equiv 112 \pmod{105} \equiv 7.

Check: 7=2⋅3+17 = 2\cdot3+1 so 7≡1(mod3)7 \equiv 1 \pmod 3; 7=1⋅5+27 = 1\cdot5+2 so 7≡2(mod5)7\equiv 2 \pmod 5; 7≡0(mod7)7 \equiv 0 \pmod 7. All hold.

Solution: x≡7(mod105)x \equiv 7 \pmod{105}, i.e. x=7,112,217,…x = 7, 112, 217, \dots

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Solve the recurrence relation T(n) = 2T(n/2) + n using recursion tree method.

Similar questions: Explain the recursion tree method for solving the recurrence (2078)

Answer

Recursion tree for T(n)=2T(n/2)+nT(n) = 2T(n/2) + n

Level 0 has one node of cost nn. Each node of size mm costs mm and has two children of size m/2m/2.

LevelNumber of nodesSize of eachCost per level
01nnnn
12n/2n/22⋅n/2=n2\cdot n/2 = n
24n/4n/44⋅n/4=n4\cdot n/4 = n
ii2i2^in/2in/2^inn
log⁡2n\log_2 nnn1n T(1)n\,T(1)

The recursion stops when n/2i=1n/2^i = 1, i.e. at depth i=log⁡2ni=\log_2 n, so the tree has log⁡2n+1\log_2 n + 1 levels. Every level contributes nn, so

T(n)=∑i=0log⁡2nn=n(log⁡2n+1)=nlog⁡2n+n.T(n) = \sum_{i=0}^{\log_2 n} n = n(\log_2 n + 1) = n\log_2 n + n.

Therefore

T(n)=Θ(nlog⁡n).T(n) = \Theta(n\log n).

This agrees with case 2 of the master theorem (merge sort recurrence).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 10 marks

What do you mean by the complexity of an algorithm? Explain the asymptotic notations used to describe the time/space complexity of any algorithm with their geometrical interpretation and example.

Answer

Complexity of an algorithm

The complexity of an algorithm measures the resources it needs as a function of the input size nn.

  • Time complexity: the number of basic operations (steps) executed, T(n)T(n).
  • Space complexity: the amount of memory used, S(n)S(n) (input plus auxiliary space).

It is analysed for the best case, average case and worst case. Since exact running time depends on the machine and language, we describe the growth rate for large nn using asymptotic notations.

Asymptotic notations

1. Big-O (upper bound). f(n)=O(g(n))f(n) = O(g(n)) if there exist constants c>0c > 0 and n0n_0 such that 0≤f(n)≤c g(n)for all n≥n0.0 \le f(n) \le c\,g(n) \quad \text{for all } n \ge n_0. Geometrically, beyond n0n_0 the curve f(n)f(n) lies on or below the curve c g(n)c\,g(n). It gives a worst-case bound. Example: 3n+2=O(n)3n + 2 = O(n), since 3n+2≤4n3n + 2 \le 4n for n≥2n \ge 2 (so c=4c = 4, n0=2n_0 = 2).

2. Big-Omega (lower bound). f(n)=Ω(g(n))f(n) = \Omega(g(n)) if there exist c>0c > 0 and n0n_0 such that 0≤c g(n)≤f(n)for all n≥n0.0 \le c\,g(n) \le f(n) \quad \text{for all } n \ge n_0. Beyond n0n_0, f(n)f(n) lies on or above c g(n)c\,g(n). It gives a best-case bound. Example: 3n+2=Ω(n)3n + 2 = \Omega(n) with c=3c = 3, n0=1n_0 = 1.

3. Big-Theta (tight bound). f(n)=Θ(g(n))f(n) = \Theta(g(n)) if there exist c1,c2>0c_1, c_2 > 0 and n0n_0 such that c1 g(n)≤f(n)≤c2 g(n)for all n≥n0.c_1\,g(n) \le f(n) \le c_2\,g(n) \quad \text{for all } n \ge n_0. Beyond n0n_0, f(n)f(n) is sandwiched between c1g(n)c_1 g(n) and c2g(n)c_2 g(n). Equivalent to f=O(g)f = O(g) and f=Ω(g)f = \Omega(g). Example: 3n+2=Θ(n)3n + 2 = \Theta(n) with c1=3c_1 = 3, c2=4c_2 = 4, n0=2n_0 = 2. Another: n22−3n=Θ(n2)\tfrac{n^2}{2} - 3n = \Theta(n^2) with c1=114c_1 = \tfrac1{14}, c2=12c_2 = \tfrac12, n0=7n_0 = 7.

4. Little-o (strict upper bound). f(n)=o(g(n))f(n) = o(g(n)) if for every c>0c > 0 there is n0n_0 with f(n)<c g(n)f(n) < c\,g(n) for all n≥n0n \ge n_0; equivalently lim⁡n→∞f(n)/g(n)=0\lim_{n\to\infty} f(n)/g(n) = 0. Example: n=o(n2)n = o(n^2) but n2≠o(n2)n^2 \ne o(n^2).

5. Little-omega (strict lower bound). f(n)=ω(g(n))f(n) = \omega(g(n)) if for every c>0c > 0 there is n0n_0 with f(n)>c g(n)f(n) > c\,g(n) for all n≥n0n \ge n_0; equivalently lim⁡f(n)/g(n)=∞\lim f(n)/g(n) = \infty. Example: n2=ω(n)n^2 = \omega(n).

Order of common growth rates: 1<log⁡n<n<nlog⁡n<n2<n3<2n<n!1 < \log n < n < n\log n < n^2 < n^3 < 2^n < n!

For example linear search is O(n)O(n), binary search is O(log⁡n)O(\log n), merge sort is Θ(nlog⁡n)\Theta(n \log n) and bubble sort is O(n2)O(n^2).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 10 marks

Explain in brief the Backtracking approach for algorithm design. How it differs with recursion? Explain the N-Queen problem and algorithm using backtracking and analyze its time complexity.

Answer

Backtracking

Backtracking is a systematic, depth-first way of searching the solution space of a problem for solutions that satisfy given constraints. The solution is built one component at a time as a vector (x1,x2,…,xn)(x_1, x_2, \dots, x_n). After each choice, a bounding (feasibility) test checks whether the partial solution can still lead to a complete valid solution. If it cannot, the algorithm abandons that branch (prunes it) and backtracks to the previous choice to try another value. The search space is viewed as a state-space tree whose nodes are partial solutions. It is used for N-Queens, graph colouring, Hamiltonian cycles, subset sum and Sudoku.

Difference from plain recursion

RecursionBacktracking
A programming technique in which a function calls itself on a smaller problem.A problem-solving strategy that normally is implemented using recursion.
Does not necessarily involve choices or search.Tries choices, and undoes a choice if it leads to failure.
Does not prune; every call is made.Prunes branches that violate constraints, reducing the search.
Examples: factorial, Fibonacci, tree traversal.Examples: N-Queens, maze solving, Sudoku.

N-Queens problem

Place NN queens on an N×NN \times N chessboard so that no two queens attack each other: no two share a row, a column or a diagonal.

Let x[i]x[i] be the column of the queen placed in row ii. This automatically gives one queen per row. Queens at (i,x[i])(i, x[i]) and (k,x[k])(k, x[k]) attack each other if they are in the same column (x[i]=x[k]x[i] = x[k]) or on the same diagonal (∣x[i]−x[k]∣=∣i−k∣|x[i] - x[k]| = |i - k|).

PLACE(k, i)            // can a queen go in row k, column i?
    for j = 1 to k - 1
        if x[j] == i or abs(x[j] - i) == abs(j - k)
            return false
    return true

NQUEENS(k, n)
    for i = 1 to n
        if PLACE(k, i)
            x[k] = i
            if k == n
                print x[1..n]
            else
                NQUEENS(k + 1, n)

Called as NQUEENS(1, n). For n=4n = 4 the solutions are (2,4,1,3)(2, 4, 1, 3) and (3,1,4,2)(3, 1, 4, 2). Working: put a queen in row 1, column 1; row 2 can only go to column 3 (columns 1 and 2 are attacked), then row 3 has no safe column, so backtrack, move queen 2 to column 4, and so on, until row 1 column 2 leads to (2,4,1,3)(2, 4, 1, 3).

Time complexity

  • PLACE takes O(k)=O(n)O(k) = O(n) time.
  • Without pruning, there would be nnn^n placements (nnn^n leaves in the state tree), or n!n! if we also require distinct columns.
  • With backtracking, the number of nodes explored is much smaller, but in the worst case it still grows factorially. At level kk there are at most n−k+1n - k + 1 candidate columns for each node, so the number of nodes is bounded by ∑k=0nn!/(n−k)!=O(n!)\sum_{k=0}^{n} n!/(n-k)! = O(n!), and each node costs O(n)O(n) for PLACE.

Hence the time complexity is O(n⋅n!)O(n \cdot n!) in the worst case (commonly stated as O(n!)O(n!)), exponential in nn. The space complexity is O(n)O(n) for the vector xx and the recursion stack.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Write the algorithm for selection sort and explain its time and space complexity.

Answer

Selection sort repeatedly selects the smallest element of the unsorted part and swaps it into the next position of the sorted part.

Algorithm

SELECTION-SORT(A, n)
1  for i = 0 to n-2
2      min = i
3      for j = i+1 to n-1
4          if A[j] < A[min]
5              min = j
6      if min != i
7          swap A[i], A[min]

Example: A = [64, 25, 12, 22, 11]. Pass 1 puts 11 first: [11, 25, 12, 22, 64]. Pass 2 puts 12 second: [11, 12, 25, 22, 64]. Pass 3 gives [11, 12, 22, 25, 64]. Pass 4 leaves the array unchanged, so the array is sorted.

Time complexity

The inner loop runs (n−1−i)(n-1-i) times for each ii, whatever the data looks like. The number of comparisons is

(n−1)+(n−2)+⋯+1=n(n−1)2(n-1)+(n-2)+\dots+1=\frac{n(n-1)}{2}

  • Best, average and worst case: Θ(n2)\Theta(n^2) comparisons. The algorithm cannot stop early, even on sorted input.
  • Swaps: at most n−1n-1, which is O(n)O(n). This is useful when writing to memory is costly.

Space complexity

Only the variables i,j,mini, j, min and one temporary for the swap are used. Space is O(1)O(1), so the sort is in place. The usual swap-based version is not stable.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Solve the following recurrence relation using the master method.
  1. T(n) = 7 T(n/2) + n^2
  2. T(n) = 4 T(n/4) + kn

Answer

The master theorem solves T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n) by comparing f(n)f(n) with nlog⁡ban^{\log_b a}.

  • Case 1: if f(n)=O(nlog⁡ba−ϵ)f(n)=O(n^{\log_b a-\epsilon}) for some ϵ>0\epsilon>0, then T(n)=Θ(nlog⁡ba)T(n)=\Theta(n^{\log_b a}).
  • Case 2: if f(n)=Θ(nlog⁡ba)f(n)=\Theta(n^{\log_b a}), then T(n)=Θ(nlog⁡balog⁡n)T(n)=\Theta(n^{\log_b a}\log n).
  • Case 3: if f(n)=Ω(nlog⁡ba+ϵ)f(n)=\Omega(n^{\log_b a+\epsilon}) and af(n/b)≤cf(n)af(n/b)\le cf(n) for some c<1c<1, then T(n)=Θ(f(n))T(n)=\Theta(f(n)).

(1) T(n)=7T(n/2)+n2T(n)=7T(n/2)+n^2

Here a=7, b=2, f(n)=n2a=7,\ b=2,\ f(n)=n^2, so nlog⁡27=n2.807n^{\log_2 7}=n^{2.807}.

Since n2=O(n2.807−ϵ)n^2=O(n^{2.807-\epsilon}) with ϵ≈0.8\epsilon\approx0.8, Case 1 applies.

T(n)=Θ(nlog⁡27)≈Θ(n2.81)T(n)=\Theta(n^{\log_2 7})\approx\Theta(n^{2.81})

(2) T(n)=4T(n/4)+knT(n)=4T(n/4)+kn

Here a=4, b=4, f(n)=kna=4,\ b=4,\ f(n)=kn, so nlog⁡44=nn^{\log_4 4}=n.

Since f(n)=kn=Θ(n)f(n)=kn=\Theta(n), Case 2 applies.

T(n)=Θ(nlog⁡n)T(n)=\Theta(n\log n)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Explain the greedy algorithm for the fractional knapsack problem with its time complexity.

Answer

Problem. There are nn items, where item ii has weight wiw_i and profit pip_i. The knapsack has capacity WW. Any fraction xi∈[0,1]x_i\in[0,1] of an item may be taken. We maximise ∑pixi\sum p_ix_i subject to ∑wixi≤W\sum w_ix_i\le W.

Greedy strategy. Take items in decreasing order of profit per unit weight pi/wip_i/w_i. Take each item wholly while it fits. Take a fraction of the first item that does not fit, and then stop.

Algorithm

FRACTIONAL-KNAPSACK(p, w, n, W)
1  for i = 1 to n: ratio[i] = p[i] / w[i]
2  sort items in decreasing order of ratio
3  remaining = W; profit = 0
4  for i = 1 to n (in sorted order)
5      if w[i] <= remaining
6          x[i] = 1; remaining -= w[i]; profit += p[i]
7      else
8          x[i] = remaining / w[i]
9          profit += x[i] * p[i]
10         break
11 return profit

Example. W=50W=50, with (p,w)=(60,10),(100,20),(120,30)(p,w)=(60,10),(100,20),(120,30). The ratios are 6, 5 and 4. Take item 1 in full (10 kg, profit 60). Take item 2 in full (20 kg, profit 100). Capacity left is 20, so take 20/3020/30 of item 3, giving profit 80. Total profit =240=240.

Correctness. Suppose an optimal solution did not use the highest-ratio item as fully as it could. Replacing some weight of a lower-ratio item with that item would not reduce the profit. So the greedy choice is safe, and the problem also has optimal substructure.

Time complexity. Computing the ratios takes O(n)O(n). Sorting takes O(nlog⁡n)O(n\log n). The selection loop takes O(n)O(n). The total is O(nlog⁡n)O(n\log n). Using a max-heap instead of a full sort gives the same bound.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Trace heap sort algorithm for the following data:
{2, 9, 3, 12, 15, 8, 11}

Answer

Heap sort first builds a max-heap, then repeatedly swaps the root (the maximum) with the last element of the heap, shrinks the heap by one, and restores the heap property with heapify.

Data (1-indexed): [2, 9, 3, 12, 15, 8, 11][2,\,9,\,3,\,12,\,15,\,8,\,11]. The children of index ii are 2i2i and 2i+12i+1.

Step 1: Build the max-heap (heapify from index 3 down to 1)

  • Index 3: 3 has children 8 and 11. Swap with 11: [2,9,11,12,15,8,3][2,9,11,12,15,8,3].
  • Index 2: 9 has children 12 and 15. Swap with 15: [2,15,11,12,9,8,3][2,15,11,12,9,8,3].
  • Index 1: 2 has children 15 and 11. Swap with 15: [15,2,11,12,9,8,3][15,2,11,12,9,8,3]. Then 2 has children 12 and 9, so swap with 12: [15,12,11,2,9,8,3][15,12,11,2,9,8,3].

The max-heap is [15,12,11,2,9,8,3][15,12,11,2,9,8,3].

Step 2: Extract the maximum repeatedly (the sorted part follows the bar)

StepSwap root with lastAfter heapify of the remaining heapSorted part
115 and 3[12,9,11,2,3,8][12,9,11,2,3,8]15
212 and 8[11,9,8,2,3][11,9,8,2,3]12, 15
311 and 3[9,3,8,2][9,3,8,2]11, 12, 15
49 and 2[8,3,2][8,3,2]9, 11, 12, 15
58 and 2[3,2][3,2]8, 9, 11, 12, 15
63 and 2[2][2]3, 8, 9, 11, 12, 15

Result: [2, 3, 8, 9, 11, 12, 15][2,\,3,\,8,\,9,\,11,\,12,\,15].

Building the heap takes O(n)O(n). Each of the n−1n-1 extractions takes O(log⁡n)O(\log n). The total is O(nlog⁡n)O(n\log n), with O(1)O(1) extra space.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

What do you mean by Dynamic programming strategy? Explain the element of DP.

Answer

Dynamic programming (DP) is a technique for solving problems by breaking them into overlapping subproblems. Each subproblem is solved only once, and its answer is stored in a table (bottom-up tabulation) or a cache (top-down memoisation). It is mainly used for optimisation problems, for example matrix chain multiplication, 0/1 knapsack, LCS and shortest paths.

Elements of dynamic programming

  1. Optimal substructure. An optimal solution to the problem contains optimal solutions to its subproblems. For example, in matrix chain multiplication, the best split of Ai…AjA_i\dots A_j uses the best parenthesisations of the two halves.
  2. Overlapping subproblems. The same subproblems occur again and again in the recursion. Storing each answer avoids recomputation. For example, a naive Fibonacci recursion computes F(n−2)F(n-2) many times. This is the feature that separates DP from divide and conquer.
  3. Recurrence (recursive formulation). The value of a problem is defined in terms of smaller ones, for example c[i][j]=min⁡k{c[i][k]+c[k+1][j]+pi−1pkpj}c[i][j]=\min_k\{c[i][k]+c[k+1][j]+p_{i-1}p_kp_j\}.
  4. Table and order of computation. A table stores the subproblem values. Subproblems are filled from the smallest to the largest, so that every value needed is already available.
  5. Construction of the solution. A second table records the choices made (for example the split point kk). The actual solution is rebuilt from it by tracing back.

Steps: characterise the structure of an optimal solution, define its value recursively, compute the values bottom-up, and construct the optimal solution from the stored information.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Explain the approximation for solving vertex cover with a suitable example.

Answer

Vertex cover problem. A vertex cover of an undirected graph G=(V,E)G=(V,E) is a set C⊆VC\subseteq V such that every edge has at least one endpoint in CC. The optimisation version asks for a cover of minimum size. This is NP-hard, so no polynomial-time exact algorithm is known.

Approximation algorithm (2-approximation)

APPROX-VERTEX-COVER(G)
1  C = empty set
2  E' = E
3  while E' is not empty
4      pick any edge (u, v) in E'
5      add both u and v to C
6      remove from E' every edge incident on u or v
7  return C

It runs in O(V+E)O(V+E) time.

Example. Take the edges E={(a,b),(b,c),(c,d),(d,e),(e,f),(d,f)}E=\{(a,b),(b,c),(c,d),(d,e),(e,f),(d,f)\}.

  • Pick (b,c)(b,c). Add b,cb,c and remove (a,b),(b,c),(c,d)(a,b),(b,c),(c,d).
  • Pick (d,e)(d,e). Add d,ed,e and remove (d,e),(e,f),(d,f)(d,e),(e,f),(d,f).
  • No edges remain, so C={b,c,d,e}C=\{b,c,d,e\} with size 4.

The optimal cover is {b,d,e}\{b,d,e\} or {b,d,f}\{b,d,f\}, of size 3, so the answer is within a factor of 2 of the optimum.

Why the ratio is 2. The edges picked in line 4 form a matching, because no two of them share a vertex. Any cover, including an optimal one C∗C^*, must contain at least one endpoint of each matched edge, so ∣C∗∣≥∣M∣|C^*|\ge|M|, where MM is the set of picked edges. The algorithm returns ∣C∣=2∣M∣≤2∣C∗∣|C|=2|M|\le2|C^*|. It is therefore a 2-approximation.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Explain Prism’s algorithm for MST problem and analyze its time complexity.

Answer

Minimum spanning tree (MST). For a connected, weighted, undirected graph, an MST is a spanning tree with the least total edge weight.

Prim's algorithm (greedy). Start from any vertex. At each step, add the cheapest edge that connects a vertex in the tree to a vertex outside it. Repeat until all VV vertices are in the tree. The cut property guarantees that every such edge belongs to some MST.

PRIM(G, w, r)
1  for each vertex u: key[u] = infinity; parent[u] = NIL
2  key[r] = 0
3  Q = all vertices (min-priority queue on key)
4  while Q is not empty
5      u = EXTRACT-MIN(Q)
6      for each v adjacent to u
7          if v in Q and w(u, v) < key[v]
8              parent[v] = u
9              key[v] = w(u, v)       // DECREASE-KEY

Example. Take the edges A-B=2, A-C=3, B-C=1, B-D=4, C-D=5A\text{-}B=2,\ A\text{-}C=3,\ B\text{-}C=1,\ B\text{-}D=4,\ C\text{-}D=5. Starting from AA, pick A-B(2)A\text{-}B(2), then B-C(1)B\text{-}C(1), then B-D(4)B\text{-}D(4). The MST weight is 7.

Time complexity

  • Adjacency matrix with a linear scan to find the minimum: O(V2)O(V^2).
  • Adjacency list with a binary min-heap: building the heap costs O(V)O(V). There are VV EXTRACT-MINs costing O(log⁡V)O(\log V) each, and up to EE DECREASE-KEYs costing O(log⁡V)O(\log V) each. The total is O(Elog⁡V)O(E\log V).
  • Fibonacci heap: O(E+Vlog⁡V)O(E+V\log V).

Prim's algorithm is best for dense graphs. Kruskal's algorithm, which runs in O(Elog⁡E)O(E\log E), is often preferred for sparse graphs.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Explain in brief about the classes P, NP, and NP complete with examples.

Answer

These classes are defined for decision problems (answer yes or no). The size of the input is nn.

Class P. The problems solvable by a deterministic algorithm in polynomial time, O(nk)O(n^k). Examples: sorting, shortest path, MST, searching, and testing whether a number is the GCD of two others.

Class NP. The problems whose proposed solution (certificate) can be verified in polynomial time. Equivalently, they are solvable in polynomial time by a non-deterministic machine. Examples: Hamiltonian cycle (a given cycle is checked in O(n)O(n)), subset sum, graph colouring, SAT. Every problem in P is also in NP, so P⊆NPP\subseteq NP. Whether P=NPP=NP is still open.

Class NP-complete (NPC). A problem LL is NP-complete if:

  1. L∈NPL\in NP, and
  2. every problem L′∈NPL'\in NP reduces to LL in polynomial time (L′≤pLL'\le_pL).

If any NP-complete problem is solved in polynomial time, then P=NPP=NP. The first NP-complete problem proved was SAT (Cook's theorem). Other examples: 3-SAT, clique, vertex cover, Hamiltonian cycle, travelling salesman (decision version), subset sum.

NP-hard problems satisfy condition 2 only. They need not be in NP, for example the halting problem. So NPC == NP ∩\cap NP-hard.

Relationship (assuming P≠NPP\ne NP): P and NPC are disjoint subsets of NP, and NP-hard contains NPC.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2076 · 5 marks

Write short notes on
  1. Backtracking strategy
  2. Tractable and Intractable Problem

Answer

(1) Backtracking strategy

Backtracking builds a solution one component at a time, as a depth-first search of the state-space tree. After each step it checks whether the partial solution can still lead to a valid complete one. If it cannot (a bounding or constraint test fails), the search abandons that branch, goes back to the previous choice, and tries the next alternative. This pruning makes it much faster than exhaustive search in practice, although the worst case is still exponential.

General scheme:

BACKTRACK(partial):
    if partial is a complete solution: output it
    for each candidate c that extends partial:
        if c is feasible (promising):
            add c; BACKTRACK(partial); remove c    // undo

Typical applications: N-queens, graph colouring, Hamiltonian cycle, subset sum, and maze solving.

(2) Tractable and intractable problems

  • Tractable problems can be solved by algorithms that run in polynomial time, O(nk)O(n^k). They are practical to solve even for large inputs. Examples: sorting (O(nlog⁡n)O(n\log n)), shortest paths and MST.
  • Intractable problems have no known polynomial-time algorithm. The best known algorithms take super-polynomial (exponential or factorial) time, for example O(2n)O(2^n) or O(n!)O(n!). They become infeasible even for moderate nn. Examples: the travelling salesman problem, Hamiltonian cycle, 0/1 knapsack (in terms of the input length), and graph colouring. Some intractable problems are shown to be NP-complete or NP-hard. In practice they are handled by approximation algorithms, heuristics or backtracking.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 10 marks

What are the elementary properties of algorithm? Explain. Why do you need algorithm? Discuss about analysis of the RAM model for analysis of algorithm with suitable example.

Answer

Elementary properties of an algorithm

An algorithm is a finite sequence of well-defined steps that solves a problem. It should have the following properties.

  1. Input: zero or more quantities are supplied from outside.
  2. Output: at least one result is produced.
  3. Definiteness: each step is precise and unambiguous.
  4. Finiteness: the algorithm terminates after a finite number of steps for every valid input.
  5. Effectiveness: every step is basic enough to be carried out exactly, in finite time.
  6. Correctness and generality: it gives the right output for all valid inputs, not only for particular ones.

Why we need algorithms

  • They give a precise, language-independent method for solving a problem, which can be checked for correctness before coding.
  • They let us compare solutions by running time and memory use, independently of the machine. For example, searching 10610^6 sorted items takes about 20 steps with binary search, but up to 10610^6 with linear search.
  • Efficient algorithms save time and resources, and they make problems feasible that would otherwise be impractical, for example sorting, routing, searching and cryptography.
  • They are the basis for programming and for reuse across applications.

RAM model of analysis

The Random Access Machine (RAM) is an abstract machine used to count the cost of an algorithm.

  • Instructions run one after another, with no concurrency.
  • Each basic operation (arithmetic, comparison, assignment, array access, branch, function call) takes one unit (constant) time.
  • Memory is unlimited, and every memory location is accessed in constant time. There is no memory hierarchy or caching.
  • Each word has a fixed size, for example enough bits to hold a number.

The running time is the number of primitive steps executed, expressed as a function T(n)T(n) of the input size nn.

Example: sum of an array

StatementCostTimes
sum = 0c1c_11
for i = 1 to nc2c_2n+1n+1
sum = sum + A[i]c3c_3nn
return sumc4c_41

T(n)=c1+c2(n+1)+c3n+c4=(c2+c3)n+(c1+c2+c4)=an+bT(n)=c_1+c_2(n+1)+c_3n+c_4=(c_2+c_3)n+(c_1+c_2+c_4)=an+b

So T(n)=Θ(n)T(n)=\Theta(n) and the running time is linear. Only the growth rate matters, so the constants are dropped.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 10 marks

Explain in brief about the Dynamic Programming Approach for algorithm design. How it differs with recursion? Explain the algorithm for solving the 0/1 Knapsack problem using the dynamic programming approach and explain its complexity.

Answer

Dynamic programming approach

Dynamic programming (DP) solves a problem by combining solutions of overlapping subproblems. It needs two properties: optimal substructure and overlapping subproblems. Each subproblem is solved once and stored in a table, then looked up whenever it is needed again. Typical steps are to define the subproblems, write a recurrence, fill the table bottom-up, and trace back to build the solution.

Difference from plain recursion

Plain recursionDynamic programming
Solves the same subproblem again every time it appears.Solves each subproblem once and stores the result.
Time is often exponential, for example naive Fibonacci in O(2n)O(2^n).Time is polynomial, for example Fibonacci in O(n)O(n).
No extra table is needed (only the call stack).Needs a table (extra memory).
Works well when subproblems are independent.Used when subproblems overlap.

0/1 knapsack by dynamic programming

There are nn items with weights wiw_i and profits pip_i, and capacity WW. Each item is taken whole or not at all. Let B[i][w]B[i][w] be the maximum profit using the first ii items with capacity ww.

B[i][w]={0i=0 or w=0B[i−1][w]wi>wmax⁡{B[i−1][w], pi+B[i−1][w−wi]}wi≤wB[i][w]=\begin{cases}0 & i=0 \text{ or } w=0\\ B[i-1][w] & w_i>w\\ \max\{B[i-1][w],\ p_i+B[i-1][w-w_i]\} & w_i\le w\end{cases}

KNAPSACK(p, w, n, W)
1  for i = 0 to n: B[i][0] = 0
2  for j = 0 to W: B[0][j] = 0
3  for i = 1 to n
4      for j = 1 to W
5          if w[i] <= j
6              B[i][j] = max(B[i-1][j], p[i] + B[i-1][j-w[i]])
7          else
8              B[i][j] = B[i-1][j]
9  return B[n][W]

The items in the solution are found by tracing back from B[n][W]B[n][W]. If B[i][j]≠B[i−1][j]B[i][j]\ne B[i-1][j], item ii is taken and jj decreases by wiw_i.

Example. W=5W=5 with (w,p)=(2,3),(3,4),(4,5),(5,6)(w,p)=(2,3),(3,4),(4,5),(5,6). The best choice is items 1 and 2, with weight 5 and profit 7, so B[4][5]=7B[4][5]=7.

Complexity

The table has (n+1)(W+1)(n+1)(W+1) entries, and each is computed in O(1)O(1) time. So the time is O(nW)O(nW) and the space is O(nW)O(nW), which can be reduced to O(W)O(W) by keeping one row. This is pseudo-polynomial, because WW is a number and not the input length.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write an algorithm to find the maximum element of an array and analyze its time complexity.

Answer

Algorithm

FIND-MAX(A, n)
1  max = A[1]
2  for i = 2 to n
3      if A[i] > max
4          max = A[i]
5  return max

The algorithm assumes the maximum is the first element. It then scans the rest of the array, replacing max whenever a larger element is seen.

Example. A = [7, 3, 9, 4]. Starting with max = 7, element 3 is smaller, 9 is larger so max = 9, and 4 is smaller. The result is 9.

Time complexity

LineCostTimes
1c1c_11
2c2c_2nn
3c3c_3n−1n-1
4c4c_4between 00 and n−1n-1
5c5c_51

The loop makes exactly n−1n-1 comparisons in every case. The assignment in line 4 runs at most n−1n-1 times, so

T(n)=an+bT(n)=an+b

The best, average and worst cases are all Θ(n)\Theta(n). The algorithm uses O(1)O(1) extra space. Every element must be examined at least once, so Ω(n)\Omega(n) is also a lower bound and the algorithm is optimal.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write the algorithm for bubble sort and explain its time complexity.

Answer

Bubble sort repeatedly compares adjacent elements and swaps them when they are in the wrong order. After pass ii, the ii largest elements have bubbled to their final places at the end.

Algorithm

BUBBLE-SORT(A, n)
1  for i = 1 to n-1
2      swapped = false
3      for j = 1 to n-i
4          if A[j] > A[j+1]
5              swap A[j], A[j+1]
6              swapped = true
7      if swapped == false
8          break

Example. A = [5, 1, 4, 2]. Pass 1 gives [1, 4, 2, 5]. Pass 2 gives [1, 2, 4, 5]. Pass 3 makes no swap, so the algorithm stops.

Time complexity

  • Pass ii makes n−in-i comparisons, so the total is (n−1)+(n−2)+⋯+1=n(n−1)2=Θ(n2)(n-1)+(n-2)+\dots+1=\frac{n(n-1)}{2}=\Theta(n^2)
  • Worst case (reverse sorted): Θ(n2)\Theta(n^2) comparisons and Θ(n2)\Theta(n^2) swaps.
  • Average case: Θ(n2)\Theta(n^2).
  • Best case (already sorted): with the swapped flag, a single pass of n−1n-1 comparisons is enough, so Θ(n)\Theta(n). Without the flag it is still Θ(n2)\Theta(n^2).

Space: O(1)O(1), in place. The sort is stable, because equal elements are never swapped.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

What do you mean by optimization problem? Explain the greedy strategy for algorithm design to
solve optimization problems.

Answer

Optimization problem

An optimization problem asks for the best solution among all feasible solutions, according to an objective function that is to be maximised or minimised. A solution that satisfies the constraints is called feasible, and the best feasible one is optimal. Examples: shortest path (minimise distance), minimum spanning tree (minimise total weight), knapsack (maximise profit), and Huffman coding (minimise the code length).

Greedy strategy

A greedy algorithm builds the solution step by step. At every step it makes the choice that looks best at that moment (the locally optimal choice), and never reconsiders it. It hopes that these local choices lead to a global optimum.

Typical structure:

  1. A candidate set from which a solution is built.
  2. A selection function that picks the best candidate.
  3. A feasibility function that checks whether the candidate can be added.
  4. An objective function and a solution test.

A greedy algorithm gives the correct optimum only when the problem has:

  • Greedy-choice property: a globally optimal solution can be reached by making a locally optimal choice.
  • Optimal substructure: after a greedy choice, the remaining problem is a smaller problem of the same kind.

Examples where greedy is optimal: fractional knapsack, activity selection, Huffman coding, Prim's and Kruskal's MST, Dijkstra's shortest path, and job sequencing with deadlines. For problems such as 0/1 knapsack greedy can fail, and dynamic programming is used.

Greedy algorithms are usually simple and fast (often O(nlog⁡n)O(n\log n) because of an initial sort).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain the algorithm and its complexity for solving job sequencing with deadline problem using greedy strategy.

Answer

Problem. There are nn jobs. Job ii has a deadline did_i and a profit pip_i, earned only if the job is finished by its deadline. Each job takes one unit of time, and only one job runs at a time. We choose a feasible set of jobs, and an order for them, to maximise total profit.

Greedy strategy. Sort the jobs in decreasing order of profit. For each job in turn, place it in the latest free time slot that is on or before its deadline. If no such slot is free, the job is rejected.

JOB-SEQUENCING(jobs, n)
1  sort jobs in decreasing order of profit
2  d_max = maximum deadline; slot[1..d_max] = empty
3  for i = 1 to n
4      for t = min(d_max, d[i]) down to 1
5          if slot[t] is empty
6              slot[t] = job i; profit += p[i]
7              break
8  return slot, profit

Example. Jobs with (deadline, profit): J1 (2, 100), J2 (1, 19), J3 (2, 27), J4 (1, 25), J5 (3, 15). Sorted by profit: J1 (100), J3 (27), J4 (25), J2 (19), J5 (15).

  • J1: deadline 2, take slot 2.
  • J3: deadline 2, slot 2 is taken, so take slot 1.
  • J4: deadline 1, slot 1 is taken, so reject.
  • J2: deadline 1, slot 1 is taken, so reject.
  • J5: deadline 3, take slot 3.

The sequence is J3, J1, J5, with profit 27+100+15=14227+100+15=142.

Complexity

  • Sorting takes O(nlog⁡n)O(n\log n).
  • The slot search takes up to O(n)O(n) per job, so the simple version takes O(n2)O(n^2) in the worst case.
  • Using a disjoint-set (union-find) structure to find the latest free slot gives about O(nlog⁡n)O(n\log n) overall.

The simple algorithm therefore runs in O(n2)O(n^2), and the improved one in O(nlog⁡n)O(n\log n).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

What do you mean by memorization strategy? Compare memorization with dynamic programing.

Answer

Memoization

Memoization is a top-down technique that speeds up a recursive algorithm by storing the result of each subproblem the first time it is computed. When the same subproblem comes up again, the stored value is returned instead of recomputing it. The word comes from "memo". A table (array or hash map) keeps the results.

Example: Fibonacci

MEMO-FIB(n)
1  if memo[n] is defined: return memo[n]
2  if n <= 1: return n
3  memo[n] = MEMO-FIB(n-1) + MEMO-FIB(n-2)
4  return memo[n]

The naive recursion takes O(2n)O(2^n) time. With memoization each F(k)F(k) is computed once, so the time is O(n)O(n).

Comparison with dynamic programming

MemoizationDynamic programming (tabulation)
Top-down: starts from the original problem and recurses down.Bottom-up: starts from the smallest subproblems and builds up.
Uses recursion with a cache.Uses iteration (loops) to fill a table.
Computes only the subproblems that are actually needed.Usually computes all subproblems in the table.
Recursive call overhead and the risk of stack overflow for deep recursion.No recursion overhead and no stack problem.
Easy to write: add a cache to the recursive solution.Needs the order of filling to be worked out in advance.

Both avoid repeated work, and both have the same asymptotic time in the usual case, which is the number of distinct subproblems times the work per subproblem.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain the concept of backtracking. How it differ with recursion?

Answer

Backtracking

Backtracking is a general method for problems where a solution is a sequence of choices (a vector (x1,…,xn)(x_1,\dots,x_n)) subject to constraints. It searches the state-space tree depth first. At each node the partial solution is extended by one choice. If the partial solution already violates a constraint (or cannot lead to a better solution), the node is pruned and the search goes back (backtracks) to the previous level to try another option. When a complete valid solution is found, it is reported (or the search continues for all solutions).

BACKTRACK(k)
    for each value v in the choices for x[k]
        x[k] = v
        if feasible(x[1..k])
            if k == n: output x
            else BACKTRACK(k+1)

Examples: N-queens, graph colouring, sum of subsets, Hamiltonian cycle, and maze solving. For example, in 4-queens, if a queen placed in row 3 has no safe column, the algorithm returns to row 2 and moves that queen.

Difference from recursion

RecursionBacktracking
A programming technique in which a function calls itself on a smaller version of the problem.An algorithm design strategy for constraint or search problems.
General purpose: used for factorial, divide and conquer, and so on.Used to search for solutions among many possibilities.
Has no notion of undoing a choice.Explicitly undoes a choice and tries another when a branch fails.
Does not prune on its own.Prunes branches that cannot lead to a solution.

Backtracking is normally implemented using recursion, so backtracking uses recursion, but not every recursive algorithm is backtracking.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Explain in brief about the complexity classes P, NP and NP Complete.

Answer

These classes are defined for decision problems (yes or no answers).

P. The class of problems that a deterministic algorithm can solve in polynomial time O(nk)O(n^k). Examples: sorting, searching, shortest path, MST. These are regarded as efficiently solvable (tractable).

NP. The class of problems for which a given solution (certificate) can be verified in polynomial time. Equivalently, they are solved in polynomial time by a non-deterministic machine. Examples: Hamiltonian cycle, subset sum, SAT, graph colouring. Every problem in P is in NP, so P⊆NPP\subseteq NP. Whether P=NPP=NP is the major open question.

NP-complete (NPC). A problem LL is NP-complete if:

  1. L∈NPL\in NP, and
  2. every problem in NP can be reduced to LL in polynomial time.

NP-complete problems are the hardest problems in NP. If any one of them is solved in polynomial time, then every problem in NP is, and P=NPP=NP. Examples: SAT (the first, by Cook's theorem), 3-SAT, clique, vertex cover, and the decision version of the travelling salesman problem.

A problem that satisfies only condition 2 is NP-hard. So NPC=NP∩NP-hardNPC=NP\cap NP\text{-hard}.

To prove a new problem NP-complete, we show it is in NP and reduce a known NP-complete problem to it in polynomial time.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2078 · 5 marks

Write short notes on:
a. NP Hard Problems and NP Completeness
b. Problem Reduction

Answer

(a) NP-hard problems and NP-completeness

A problem HH is NP-hard if every problem in NP can be reduced to HH in polynomial time. NP-hard problems are at least as hard as every problem in NP. They need not be decision problems and need not be in NP. Examples: the halting problem, the optimisation travelling salesman problem.

A problem is NP-complete if it is both in NP and NP-hard. So NP-complete problems are the hardest problems inside NP. Examples: SAT, 3-SAT, clique, vertex cover, Hamiltonian cycle, subset sum.

Consequences:

  • If one NP-complete problem has a polynomial-time algorithm, then P=NPP=NP.
  • If P≠NPP\ne NP, no NP-complete problem can be solved in polynomial time.
  • Cook's theorem showed that SAT is NP-complete. Other problems are then proved NP-complete by reduction from known NP-complete problems.

(b) Problem reduction

A problem AA is reducible to a problem BB (A≤pBA\le_pB) if there is a polynomial-time function ff that converts any instance xx of AA into an instance f(x)f(x) of BB, such that

x is a yes-instance of A  ⟺  f(x) is a yes-instance of Bx \text{ is a yes-instance of } A \iff f(x) \text{ is a yes-instance of } B

So an algorithm for BB, with the conversion, solves AA. Meaning:

  • If BB is easy (in P), then AA is easy.
  • If AA is hard (NP-complete), then BB is at least as hard.

Example: the Hamiltonian cycle problem reduces to the travelling salesman problem. Give the edges of the graph cost 1 and the missing edges cost 2. The graph has a Hamiltonian cycle if and only if the tour has cost at most nn.

Reduction is the main tool for proving NP-completeness: show the problem is in NP, then reduce a known NP-complete problem to it.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 10 marks

Explain the divide and conquer strategy for problem solving. Describe the worst-case linear time selection algorithm and analyze its complexity.

Answer

Divide and conquer

This strategy has three steps.

  1. Divide the problem into smaller subproblems of the same type.
  2. Conquer them by solving them recursively. Small subproblems are solved directly.
  3. Combine the sub-solutions to get the solution of the original problem.

The time is described by T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n). Examples: merge sort, quick sort, binary search, Strassen's matrix multiplication.

Selection problem. Find the ii-th smallest element of an array of nn distinct elements. Sorting would take O(nlog⁡n)O(n\log n). Randomized-select has expected time O(n)O(n) but its worst case is O(n2)O(n^2). The median-of-medians algorithm guarantees O(n)O(n) in the worst case.

SELECT(A, n, i)

  1. Divide the nn elements into ⌈n/5⌉\lceil n/5\rceil groups of 5 elements (the last group may be smaller).
  2. Sort each group (insertion sort) and find its median.
  3. Recursively call SELECT to find xx, the median of these ⌈n/5⌉\lceil n/5\rceil medians.
  4. Partition the array around xx. Let kk be the rank of xx, so k−1k-1 elements are less than xx.
  5. If i=ki=k, return xx. If i<ki<k, recursively select the ii-th smallest in the lower part. Otherwise select the (i−k)(i-k)-th smallest in the upper part.

Analysis

At least half of the ⌈n/5⌉\lceil n/5\rceil group medians are ≥x\ge x. Each of those groups (except possibly the last and the group containing xx) has at least 3 elements ≥x\ge x. So the number of elements greater than xx is at least

3(⌈12⌈n5⌉⌉−2)≥3n10−63\left(\left\lceil\frac12\left\lceil\frac n5\right\rceil\right\rceil-2\right)\ge\frac{3n}{10}-6

By symmetry, at least 3n/10−63n/10-6 elements are less than xx. So in step 5 the recursion is on at most 7n/10+67n/10+6 elements.

Costs: steps 1, 2 and 4 take O(n)O(n). Step 3 takes T(⌈n/5⌉)T(\lceil n/5\rceil). Step 5 takes at most T(7n/10+6)T(7n/10+6). Hence

T(n)≤T(⌈n/5⌉)+T(7n/10+6)+O(n)T(n)\le T(\lceil n/5\rceil)+T(7n/10+6)+O(n)

Guess T(n)≤cnT(n)\le cn. Then, for large nn,

T(n)≤cn5+c(7n10+6)+an=9cn10+6c+an=cn−(cn10−6c−an)≤cnT(n)\le c\frac n5+c\left(\frac{7n}{10}+6\right)+an=\frac{9cn}{10}+6c+an=cn-\left(\frac{cn}{10}-6c-an\right)\le cn

provided cn10−6c−an≥0\frac{cn}{10}-6c-an\ge0, which holds for a large enough constant cc and n≥n\ge some n0n_0 (for example c≥20ac\ge20a and n≥120n\ge120).

Therefore the worst-case time is T(n)=O(n)T(n)=O(n). The groups of 5 are essential: because 1/5+7/10<11/5+7/10<1, the work shrinks geometrically.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 10 marks

Write the dynamic programming algorithm for matrix chain multiplication. Find the optimal parenthesization for the matrix chain product ABCD with size of each is given as A_5×10 , B_10×15 , C_15×20 , D_20×30

Answer

Matrix chain multiplication

Given matrices A1,…,AnA_1,\dots,A_n with AiA_i of size pi−1×pip_{i-1}\times p_i, find the parenthesisation that minimises the number of scalar multiplications. Multiplying a p×qp\times q matrix by a q×rq\times r matrix costs pqrpqr.

Let m[i][j]m[i][j] be the minimum cost of Ai⋯AjA_i\cdots A_j.

m[i][j]={0i=jmin⁡i≤k<j{m[i][k]+m[k+1][j]+pi−1pkpj}i<jm[i][j]=\begin{cases}0 & i=j\\ \min_{i\le k<j}\{m[i][k]+m[k+1][j]+p_{i-1}p_kp_j\} & i<j\end{cases}

MATRIX-CHAIN-ORDER(p, n)
1  for i = 1 to n: m[i][i] = 0
2  for L = 2 to n                    // chain length
3      for i = 1 to n-L+1
4          j = i + L - 1
5          m[i][j] = infinity
6          for k = i to j-1
7              q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j]
8              if q < m[i][j]
9                  m[i][j] = q; s[i][j] = k
10 return m, s

The time is O(n3)O(n^3) and the space is O(n2)O(n^2). The parenthesisation is rebuilt from the table ss.

Problem. AA is 5×105\times10, BB is 10×1510\times15, CC is 15×2015\times20, DD is 20×3020\times30. So p=[5,10,15,20,30]p=[5,10,15,20,30].

Chain length 2

  • m[1][2]=5⋅10⋅15=750m[1][2]=5\cdot10\cdot15=750
  • m[2][3]=10⋅15⋅20=3000m[2][3]=10\cdot15\cdot20=3000
  • m[3][4]=15⋅20⋅30=9000m[3][4]=15\cdot20\cdot30=9000

Chain length 3

  • m[1][3]=min⁡{k=1: m[2][3]+5⋅10⋅20=3000+1000=4000; k=2: m[1][2]+5⋅15⋅20=750+1500=2250}=2250m[1][3]=\min\{k{=}1:\ m[2][3]+5\cdot10\cdot20=3000+1000=4000;\ k{=}2:\ m[1][2]+5\cdot15\cdot20=750+1500=2250\}=2250 with s=2s=2.
  • m[2][4]=min⁡{k=2: m[3][4]+10⋅15⋅30=9000+4500=13500; k=3: m[2][3]+10⋅20⋅30=3000+6000=9000}=9000m[2][4]=\min\{k{=}2:\ m[3][4]+10\cdot15\cdot30=9000+4500=13500;\ k{=}3:\ m[2][3]+10\cdot20\cdot30=3000+6000=9000\}=9000 with s=3s=3.

Chain length 4

  • k=1k=1: m[2][4]+5⋅10⋅30=9000+1500=10500m[2][4]+5\cdot10\cdot30=9000+1500=10500
  • k=2k=2: m[1][2]+m[3][4]+5⋅15⋅30=750+9000+2250=12000m[1][2]+m[3][4]+5\cdot15\cdot30=750+9000+2250=12000
  • k=3k=3: m[1][3]+m[4][4]+5⋅20⋅30=2250+0+3000=5250m[1][3]+m[4][4]+5\cdot20\cdot30=2250+0+3000=5250

So m[1][4]=5250m[1][4]=5250 with s=3s=3.

m[i][j]m[i][j]1234
1075022505250
2030009000
309000
40

Optimal parenthesisation. The first split is at k=3k=3, giving (A1A2A3)A4(A_1A_2A_3)A_4. Since s[1][3]=2s[1][3]=2, the first part is (A1A2)A3(A_1A_2)A_3.

((AB)C)D((AB)C)D

The minimum number of scalar multiplications is 5250.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Explain the iterative algorithm to find the GCD of given two numbers and analyze its complexity.

Answer

Euclid's iterative algorithm

The greatest common divisor of aa and bb is found from the identity gcd⁡(a,b)=gcd⁡(b, a mod b)\gcd(a,b)=\gcd(b,\ a\bmod b) and gcd⁡(a,0)=a\gcd(a,0)=a. The pair is replaced repeatedly by (b, a mod b)(b,\ a\bmod b) until the remainder is 0.

GCD(a, b)
1  while b != 0
2      r = a mod b
3      a = b
4      b = r
5  return a

Example. gcd⁡(48,18)\gcd(48,18): (48,18)→(18,12)→(12,6)→(6,0)(48,18)\to(18,12)\to(12,6)\to(6,0). The answer is 6.

Complexity

Each iteration does a constant amount of work, so the cost is the number of iterations.

Claim: if a≥ba\ge b, then a mod b<a/2a\bmod b<a/2. If b≤a/2b\le a/2, then a mod b<b≤a/2a\bmod b<b\le a/2. If b>a/2b>a/2, then a mod b=a−b<a/2a\bmod b=a-b<a/2.

After two iterations, the pair (a,b)(a,b) becomes (a′,b′)(a',b') with a′=r1<a/2a'=r_1<a/2, and the new first argument is again halved. So the larger value at least halves every two iterations, which gives at most about 2log⁡2a2\log_2 a iterations. (Lamé's theorem gives a sharper bound: the worst case occurs for consecutive Fibonacci numbers, with about log⁡ϕb\log_\phi b iterations, ϕ≈1.618\phi\approx1.618.)

T(a,b)=O(log⁡min⁡(a,b))T(a,b)=O(\log\min(a,b))

This is linear in the number of bits of the input. The space is O(1)O(1).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Generate the prefix code for the string ” CYBER CRIME” using Huffman algorithm and find the total number of bits required.

Answer

Huffman coding. Huffman's greedy algorithm builds an optimal prefix code. The two least frequent nodes are repeatedly merged into a new node whose frequency is their sum, until one tree remains. Left edges are labelled 0 and right edges 1.

Frequencies. The string "CYBER CRIME" has 11 characters (the space counts as one character).

SymbolCERYBspaceIM
Frequency22211111

Building the tree

  1. Merge Y(1) and B(1) to get N1 = 2.
  2. Merge space(1) and I(1) to get N2 = 2.
  3. Merge M(1) and C(2) to get N3 = 3.
  4. Merge E(2) and R(2) to get N4 = 4.
  5. Merge N1(2) and N2(2) to get N5 = 4.
  6. Merge N3(3) and N4(4) to get N6 = 7.
  7. Merge N5(4) and N6(7) to get the root = 11.

Codes (left 0, right 1)

SymbolCodeLengthFrequencyBits
Y000313
B001313
space010313
I011313
M100313
C101326
E110326
R111326

Total bits =3+3+3+3+3+6+6+6=33=3+3+3+3+3+6+6+6=33.

Check: the sum of the internal node weights is 2+2+3+4+4+7+11=332+2+3+4+4+7+11=33, which agrees.

Total number of bits required = 33. The encoded string uses 33 bits, compared with 88 bits in 8-bit ASCII (11 characters). The tree turns out to be balanced, so each symbol has a 3-bit code, which equals the cost of a fixed-length 3-bit code for 8 symbols.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Define tractable and intractable problem. Illustrate vertex cover problem with an example.

Answer

Tractable and intractable problems

A problem is tractable if it can be solved by an algorithm whose running time is bounded by a polynomial in the input size nn, i.e. O(nk)O(n^k) for some constant kk. These problems form the class P (sorting, shortest path, minimum spanning tree, matrix multiplication).

A problem is intractable if no polynomial-time algorithm is known (or can exist) and the best known algorithms take super-polynomial time such as O(2n)O(2^n) or O(n!)O(n!). Even for modest nn these are impractical. Examples: travelling salesman, Hamiltonian cycle, vertex cover, subset sum (decision versions are NP-complete).

Vertex cover problem

Given an undirected graph G=(V,E)G=(V,E), a vertex cover is a subset V′⊆VV'\subseteq V such that every edge (u,v)∈E(u,v)\in E has at least one endpoint in V′V'. The optimisation problem asks for a cover of minimum size; the decision version asks "is there a cover of size ≤k\le k?", which is NP-complete.

Example. Let V={1,2,3,4,5}V=\{1,2,3,4,5\} and E={(1,2),(1,3),(2,3),(3,4),(4,5)}E=\{(1,2),(1,3),(2,3),(3,4),(4,5)\}.

  • {1,2,3,4,5}\{1,2,3,4,5\} is a cover, but not minimal.
  • {1,3,4}\{1,3,4\}: edge (1,2) is covered by 1, (1,3) by 1 and 3, (2,3) by 3, (3,4) by 3 and 4, (4,5) by 4. Every edge is covered, so it is a cover of size 3.
  • Can size 2 work? The triangle 1-2-3 needs at least 2 vertices, and then edge (4,5) needs a further vertex, so at least 3 are needed. Hence the minimum vertex cover has size 3, e.g. {1,3,4}\{1,3,4\} or {2,3,4}\{2,3,4\}.

Since finding the exact minimum is intractable, a 2-approximation is used: repeatedly pick an uncovered edge (u,v)(u,v), add both uu and vv to the cover, and delete all edges incident on uu or vv. On the example, picking (1,2) removes edges (1,2), (1,3), (2,3); picking (3,4) then removes (3,4) and (4,5). The cover is {1,2,3,4}\{1,2,3,4\} of size 4, which is at most twice the optimum 3.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Find the edit distance between the string ” ARTIFICIAL” and “NATURAL” Using dynamic programming.

Answer

Edit distance allows insertion, deletion and substitution, each of cost 1. Let A=A= ARTIFICIAL (m=10m=10) and B=B= NATURAL (n=7n=7). Let D[i][j]D[i][j] be the distance between the first ii letters of AA and the first jj letters of BB.

D[i][j]={ij=0ji=0min⁡(D[i−1][j]+1, D[i][j−1]+1, D[i−1][j−1]+[Ai≠Bj])otherwiseD[i][j]=\begin{cases} i & j=0\\ j & i=0\\ \min\big(D[i-1][j]+1,\ D[i][j-1]+1,\ D[i-1][j-1]+[A_i\ne B_j]\big) & \text{otherwise}\end{cases}

Filling the table row by row:

ε\varepsilonNATURAL
ε\varepsilon01234567
A11123456
R22223345
T33323445
I44433455
F55544456
I66655556
C77766666
I88877777
A99888878
L1010999987

Hence D[10][7]=7D[10][7]=7, so the edit distance is 7.

One optimal sequence of operations (found by tracing back): substitute A→N, substitute R→A, keep T, substitute I→U, substitute F→R, delete I, delete C, delete I, keep A, keep L. That is 4 substitutions and 3 deletions, 7 operations.

Time and space are O(mn)O(mn).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Write short notes on:
a) Best, Worst and average case complexity
b) Greedy Strategy

Answer

(a) Best, worst and average case complexity

The running time of an algorithm often depends on which input of size nn is given.

  • Best case: the input for which the algorithm does the least work; it gives the lower bound Ω\Omega. For linear search the key is the first element, T(n)=1T(n)=1, O(1)O(1). For insertion sort, an already sorted array gives O(n)O(n).
  • Worst case: the input forcing the most work; it gives an upper bound OO that holds for every input. For linear search the key is last or absent, O(n)O(n). For insertion sort a reverse-sorted array gives O(n2)O(n^2). Worst case is the most commonly quoted measure because it is a guarantee.
  • Average case: the expected running time over all inputs of size nn, assuming a probability distribution (usually uniform). For linear search with a successful search, the average number of comparisons is 1+2+⋯+nn=n+12=O(n)\frac{1+2+\dots+n}{n}=\frac{n+1}{2}=O(n). For quick sort it is O(nlog⁡n)O(n\log n). It is harder to compute because it needs the input distribution.

(b) Greedy strategy

A greedy algorithm builds the solution step by step, and at each step picks the choice that looks best locally (the greedy choice) without reconsidering earlier decisions. It gives an optimal solution when the problem has

  1. the greedy-choice property: a globally optimal solution can be reached by making locally optimal choices, and
  2. optimal substructure: after a choice, the remaining subproblem's optimal solution combines with the choice to give the overall optimum.

Typical components: a candidate set, a selection function, a feasibility check, and an objective function. Examples where greedy is optimal: fractional knapsack, activity selection, Huffman coding, Kruskal's and Prim's MST, Dijkstra's shortest path (non-negative weights), job sequencing with deadlines. It fails for 0/1 knapsack and travelling salesman. Greedy algorithms are usually simple and fast, e.g. O(nlog⁡n)O(n\log n) after sorting.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Solve the following recurrence relations using masters method
a. T(n) = 2T(n/4) + kn^2, n > 1
=1 , n=1
b. T(n) = 5T(n/4) + kn , n > 1
=1 , n=1

Answer

Master theorem: for T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n) compare f(n)f(n) with nlog⁡ban^{\log_b a}.

  1. If f(n)=O(nlog⁡ba−ϵ)f(n)=O(n^{\log_b a-\epsilon}) for some ϵ>0\epsilon>0, then T(n)=Θ(nlog⁡ba)T(n)=\Theta(n^{\log_b a}).
  2. If f(n)=Θ(nlog⁡ba)f(n)=\Theta(n^{\log_b a}), then T(n)=Θ(nlog⁡balog⁡n)T(n)=\Theta(n^{\log_b a}\log n).
  3. If f(n)=Ω(nlog⁡ba+ϵ)f(n)=\Omega(n^{\log_b a+\epsilon}) and af(n/b)≤cf(n)af(n/b)\le cf(n) for some c<1c<1, then T(n)=Θ(f(n))T(n)=\Theta(f(n)).

(a) T(n)=2T(n/4)+kn2T(n)=2T(n/4)+kn^2.

Here a=2a=2, b=4b=4, so nlog⁡42=n1/2n^{\log_4 2}=n^{1/2}. Since f(n)=kn2=Ω(n1/2+ϵ)f(n)=kn^2=\Omega(n^{1/2+\epsilon}) (take ϵ=3/2\epsilon=3/2), case 3 applies. Regularity check:

2f(n/4)=2kn216=18kn2≤18f(n)2f(n/4)=2k\frac{n^2}{16}=\frac{1}{8}kn^2\le \frac18 f(n)

so c=1/8<1c=1/8<1. Therefore T(n)=Θ(n2)T(n)=\Theta(n^2).

(b) T(n)=5T(n/4)+knT(n)=5T(n/4)+kn.

Here a=5a=5, b=4b=4, so nlog⁡45≈n1.161n^{\log_4 5}\approx n^{1.161}. Since f(n)=kn=O(n1.161−ϵ)f(n)=kn=O(n^{1.161-\epsilon}) with ϵ≈0.161\epsilon\approx0.161, case 1 applies. Therefore

T(n)=Θ(nlog⁡45)≈Θ(n1.16).T(n)=\Theta\big(n^{\log_4 5}\big)\approx\Theta(n^{1.16}).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2079 · 5 marks

Trace the quick sort algorithm for sorting the array A[ ]={15,7,6,23, 18,34,25} and write it’s best and worst complexity.

Answer

Quick sort picks a pivot, partitions the array so that elements ≤\le pivot lie to its left and larger elements to its right, and recursively sorts both parts. Here the last element is the pivot (Lomuto partition).

A=[15,7,6,23,18,34,25]A=[15,7,6,23,18,34,25]

Pass 1 (pivot 25): scanning 15, 7, 6, 23, 18 are all ≤25\le25 and stay in place; 34 is larger. Place the pivot after the small elements by swapping 34 and 25:

[15,7,6,23,18,25,34][15,7,6,23,18,\mathbf{25},34]. Pivot is in its final position (index 5). Left part [15,7,6,23,18][15,7,6,23,18], right part [34][34] (single element, done).

Pass 2 (left part, pivot 18): 15, 7, 6 are ≤18\le18, 23 is larger. Swap 23 and 18:

[15,7,6,18,23][15,7,6,\mathbf{18},23]. Left [15,7,6][15,7,6], right [23][23] (done).

Pass 3 (pivot 6): 15 and 7 are both greater than 6, so swap 15 with the pivot:

[6,7,15][\mathbf{6},7,15]. Left is empty, right is [7,15][7,15].

Pass 4 (pivot 15): 7 ≤\le 15, so nothing moves: [7,15][7,\mathbf{15}]; the single remaining element 7 is sorted.

Final sorted array: [6,7,15,18,23,25,34][6,7,15,18,23,25,34].

Complexity

Partitioning nn elements costs Θ(n)\Theta(n).

  • Best case: the pivot always splits the array into two halves, T(n)=2T(n/2)+Θ(n)T(n)=2T(n/2)+\Theta(n), giving Θ(nlog⁡n)\Theta(n\log n).
  • Worst case: the pivot is always the smallest or largest element (already sorted or reverse-sorted input with this pivot rule), T(n)=T(n−1)+Θ(n)T(n)=T(n-1)+\Theta(n), giving Θ(n2)\Theta(n^2).
  • Average case is Θ(nlog⁡n)\Theta(n\log n).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

What is recurrence relation? How it can be solved? Show that time complexity of the recurrence relation T(n) = 2T(n/2) + 1 is O(n) using substitution method.

Answer

Recurrence relation

A recurrence relation expresses the running time of a recursive algorithm on input size nn in terms of its running time on smaller inputs, together with a base case. For divide and conquer it has the form T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n), where aa subproblems of size n/bn/b are solved and f(n)f(n) is the cost of dividing and combining. Merge sort, for example, gives T(n)=2T(n/2)+nT(n)=2T(n/2)+n.

Methods of solving

  1. Substitution method: guess the form of the solution and prove it by mathematical induction, finding the constants.
  2. Recursion-tree method: expand the recurrence into a tree, find the cost of each level, and sum over all levels (the result is often used as a guess for substitution).
  3. Master method: for T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n), compare f(n)f(n) with nlog⁡ban^{\log_b a} and read off the answer from one of three cases.
  4. Iteration (expansion) method: repeatedly expand the recurrence until the base case, then sum the series.

Show that T(n)=2T(n/2)+1T(n)=2T(n/2)+1 is O(n)O(n) by substitution (with T(1)=1T(1)=1)

Naive guess. Assume T(n)≤cnT(n)\le cn for all smaller values. Then

T(n)≤2cn2+1=cn+1,T(n)\le 2c\frac n2+1=cn+1,

which is not ≤cn\le cn, so the induction does not close (even though the claim is true). We strengthen the hypothesis by subtracting a lower-order term.

Strengthened hypothesis. Claim T(n)≤cn−dT(n)\le cn-d for constants c,d>0c,d>0.

Inductive step: assume it holds for n/2n/2, i.e. T(n/2)≤cn2−dT(n/2)\le c\frac n2-d. Then

T(n)=2T(n/2)+1≤2(cn2−d)+1=cn−2d+1.T(n)=2T(n/2)+1\le 2\left(c\frac n2-d\right)+1=cn-2d+1.

We need cn−2d+1≤cn−dcn-2d+1\le cn-d, which holds when d≥1d\ge1. Take d=1d=1.

Base case: T(1)=1≤c⋅1−d=c−1T(1)=1\le c\cdot1-d=c-1 requires c≥2c\ge2. Take c=2c=2.

So T(n)≤2n−1T(n)\le 2n-1 for all n≥1n\ge1, hence T(n)=O(n)T(n)=O(n). ■\blacksquare

(Check with the master theorem: a=2,b=2a=2,b=2, nlog⁡22=nn^{\log_2 2}=n, f(n)=1=O(n1−ϵ)f(n)=1=O(n^{1-\epsilon}), so T(n)=Θ(n)T(n)=\Theta(n).)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Write down the advantages of dynamic programming over greedy strategy. Find optimal bracketing to multiply 4 matrices of order 2,3,4,2,5.

Answer

Advantages of dynamic programming over greedy strategy

  • Dynamic programming (DP) considers all relevant subproblems and combines their results, so it always gives an optimal solution for problems with optimal substructure and overlapping subproblems. Greedy commits to a locally best choice and may miss the global optimum (e.g. 0/1 knapsack, coin change with arbitrary denominations, shortest paths with negative edges).
  • DP does not need the greedy-choice property, which is hard to prove and often false.
  • DP stores subproblem answers in a table (memoisation/tabulation), so it avoids recomputing overlapping subproblems and turns exponential brute-force into polynomial time.
  • DP can reconstruct the solution itself (not only its value) by keeping the choices made.
  • Greedy is faster and uses less memory, but DP is the safe choice when greedy fails.

Matrix chain multiplication for dimensions 2, 3, 4, 2, 5

Matrices: A1:2×3A_1:2\times3, A2:3×4A_2:3\times4, A3:4×2A_3:4\times2, A4:2×5A_4:2\times5, with p=(2,3,4,2,5)p=(2,3,4,2,5).

m[i][j]=min⁡i≤k<j(m[i][k]+m[k+1][j]+pi−1pkpj),m[i][i]=0.m[i][j]=\min_{i\le k<j}\big(m[i][k]+m[k+1][j]+p_{i-1}p_kp_j\big),\quad m[i][i]=0.

Chains of length 2:

  • m[1][2]=2⋅3⋅4=24m[1][2]=2\cdot3\cdot4=24
  • m[2][3]=3⋅4⋅2=24m[2][3]=3\cdot4\cdot2=24
  • m[3][4]=4⋅2⋅5=40m[3][4]=4\cdot2\cdot5=40

Chains of length 3:

  • m[1][3]m[1][3]: k=1k=1: 0+24+2⋅3⋅2=360+24+2\cdot3\cdot2=36; k=2k=2: 24+0+2⋅4⋅2=4024+0+2\cdot4\cdot2=40. Minimum 36, k=1k=1.
  • m[2][4]m[2][4]: k=2k=2: 0+40+3⋅4⋅5=1000+40+3\cdot4\cdot5=100; k=3k=3: 24+0+3⋅2⋅5=5424+0+3\cdot2\cdot5=54. Minimum 54, k=3k=3.

Chain of length 4:

  • m[1][4]m[1][4]: k=1k=1: 0+54+2⋅3⋅5=840+54+2\cdot3\cdot5=84; k=2k=2: 24+40+2⋅4⋅5=10424+40+2\cdot4\cdot5=104; k=3k=3: 36+0+2⋅2⋅5=5636+0+2\cdot2\cdot5=56. Minimum 56, k=3k=3.
m[i][j]m[i][j]j=1j=2j=3j=4
i=10243656
i=202454
i=3040
i=40

The best split of A1..A4A_1..A_4 is at k=3k=3, and for A1..A3A_1..A_3 at k=1k=1. The optimal bracketing is

(A1 (A2A3)) A4\big(A_1\,(A_2A_3)\big)\,A_4

with minimum cost 24+12+20=5624+12+20=56 scalar multiplications (A2A3A_2A_3: 24; A1(A2A3)A_1(A_2A_3): 2⋅3⋅2=122\cdot3\cdot2=12; times A4A_4: 2⋅2⋅5=202\cdot2\cdot5=20).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 10 marks

Discuss heapify operation with example. Write down its algorithm and analyze its time and space complexity.

Answer

Heapify

A (max-)heap is a complete binary tree stored in an array in which every node is ≥\ge its children. With 1-based indexing, the children of node ii are 2i2i and 2i+12i+1 and the parent is ⌊i/2⌋\lfloor i/2\rfloor.

Heapify (Max-Heapify) restores the heap property at node ii when the subtrees rooted at its children are already heaps but A[i]A[i] may be smaller than a child. It "sinks" A[i]A[i] down: compare it with its children, swap it with the larger child if needed, and continue down that path.

Example. A=[4,10,3,5,1]A=[4,10,3,5,1], heapify at i=1i=1.

  • Children of 4 are 10 and 3. The larger is 10, so swap: [10,4,3,5,1][10,4,3,5,1].
  • Now 4 is at index 2, with children 5 (index 4) and 1 (index 5). Larger is 5 and 5>45>4, so swap: [10,5,3,4,1][10,5,3,4,1].
  • 4 is at index 4 with no children, so stop. Result [10,5,3,4,1][10,5,3,4,1] is a max-heap.

Algorithm

MAX-HEAPIFY(A, i, n)
    l = 2*i
    r = 2*i + 1
    largest = i
    if l <= n and A[l] > A[largest]
        largest = l
    if r <= n and A[r] > A[largest]
        largest = r
    if largest != i
        swap A[i] and A[largest]
        MAX-HEAPIFY(A, largest, n)

Time complexity

Each call does Θ(1)\Theta(1) work (comparisons and one swap) and then recurses on one child. A child's subtree has at most 2n/32n/3 nodes (worst case when the last level of the tree is exactly half full). Hence

T(n)≤T(2n/3)+Θ(1).T(n)\le T(2n/3)+\Theta(1).

By the master theorem (a=1,b=3/2a=1,b=3/2, nlog⁡ba=n0=1=Θ(f(n))n^{\log_b a}=n^0=1=\Theta(f(n)), case 2), T(n)=Θ(log⁡n)T(n)=\Theta(\log n). Equivalently the running time is O(h)O(h) where h=⌊log⁡2n⌋h=\lfloor\log_2 n\rfloor is the height of node ii. The best case (node already in place) is O(1)O(1).

Space complexity

Heapify works in place. The recursive version uses O(log⁡n)O(\log n) stack space (depth equals tree height); the iterative version (replace the recursive call by a loop) uses O(1)O(1) extra space.

Applying heapify bottom-up for i=⌊n/2⌋i=\lfloor n/2\rfloor down to 1 builds a heap in O(n)O(n) time and is the basis of heap sort.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Define RAM model. Write down iterative algorithm for finding factorial and provide its detailed analysis.

Answer

RAM model

The Random Access Machine (RAM) is the standard abstract machine used to analyse algorithms. Its assumptions are:

  • instructions execute one after another, with no concurrency;
  • each basic operation (arithmetic, comparison, assignment, data movement, control such as branching and function call/return) takes one unit (constant) of time;
  • memory is unlimited, and any memory location is accessed in constant time;
  • integers and words have a fixed size, and the model has no cache or memory hierarchy.

The running time is the number of primitive steps executed, expressed as a function of the input size nn.

Iterative factorial

FACTORIAL(n)
1   fact = 1
2   for i = 2 to n
3       fact = fact * i
4   return fact

Detailed analysis (cost ckc_k per execution of line kk)

LineCostTimes executed
1c1c_11
2 (loop test)c2c_2nn (loop runs n−1n-1 times, plus the final failing test)
3c3c_3n−1n-1
4c4c_41

T(n)=c1+c2n+c3(n−1)+c4=(c2+c3)n+(c1+c4−c3)=an+b.T(n)=c_1+c_2n+c_3(n-1)+c_4=(c_2+c_3)n+(c_1+c_4-c_3)=an+b.

So T(n)=Θ(n)T(n)=\Theta(n) (linear). The best, worst and average cases are the same because the loop always runs n−1n-1 times.

Space: only the variables n, i and fact are used, so the auxiliary space is Θ(1)\Theta(1). (If big numbers are considered, n!n! has Θ(nlog⁡n)\Theta(n\log n) bits, but in the RAM model it is one word.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write down algorithm of insertion sort and analyze its time and space complexity.

Answer

Insertion sort builds a sorted prefix: it takes the next element (the key) and inserts it into its correct place among the already sorted elements on its left, shifting larger elements one place right.

INSERTION-SORT(A, n)
1   for j = 2 to n
2       key = A[j]
3       i = j - 1
4       while i > 0 and A[i] > key
5           A[i+1] = A[i]
6           i = i - 1
7       A[i+1] = key

Time analysis. Let tjt_j be the number of times the while-test is executed for a given jj.

LineCostTimes
1c1c_1nn
2c2c_2n−1n-1
3c3c_3n−1n-1
4c4c_4∑j=2ntj\sum_{j=2}^{n}t_j
5c5c_5∑j=2n(tj−1)\sum_{j=2}^{n}(t_j-1)
6c6c_6∑j=2n(tj−1)\sum_{j=2}^{n}(t_j-1)
7c7c_7n−1n-1
  • Best case (already sorted): tj=1t_j=1, so T(n)=an+bT(n)=an+b, i.e. Θ(n)\Theta(n).
  • Worst case (reverse sorted): tj=jt_j=j, with ∑j=2nj=n(n+1)2−1\sum_{j=2}^n j=\frac{n(n+1)}2-1 and ∑j=2n(j−1)=n(n−1)2\sum_{j=2}^n (j-1)=\frac{n(n-1)}{2}, so T(n)=an2+bn+cT(n)=an^2+bn+c, i.e. Θ(n2)\Theta(n^2).
  • Average case: about half the elements of the prefix are shifted, tj≈j/2t_j\approx j/2, still Θ(n2)\Theta(n^2).

Space complexity. Sorting is in place; only key, i, j are extra, so O(1)O(1) auxiliary space. The sort is stable and efficient for small or nearly sorted arrays.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write down minmax algorithm and analyze its complexity.

Answer

The MinMax problem finds the minimum and maximum of nn numbers. The divide and conquer approach splits the array into two halves, finds min and max in each half recursively, and combines them.

MINMAX(A, low, high)
    if low == high                    // one element
        return (A[low], A[low])
    if high == low + 1                // two elements
        if A[low] < A[high]
            return (A[low], A[high])
        else
            return (A[high], A[low])
    mid = (low + high) / 2
    (min1, max1) = MINMAX(A, low, mid)
    (min2, max2) = MINMAX(A, mid+1, high)
    min = (min1 < min2) ? min1 : min2
    max = (max1 > max2) ? max1 : max2
    return (min, max)

Complexity (number of comparisons). Let T(n)T(n) be the number of comparisons.

T(n)={0n=11n=22T(n/2)+2n>2T(n)=\begin{cases}0 & n=1\\ 1 & n=2\\ 2T(n/2)+2 & n>2\end{cases}

The 2 extra comparisons are for combining min and max. For nn a power of 2, expanding:

T(n)=2T(n/2)+2=4T(n/4)+4+2=⋯=2k−1T(2)+∑i=1k−12i=n2+(n−2)=3n2−2,T(n)=2T(n/2)+2=4T(n/4)+4+2=\dots=2^{k-1}T(2)+\sum_{i=1}^{k-1}2^i = \frac n2+(n-2)=\frac{3n}{2}-2,

where n=2kn=2^k. Hence T(n)=3n2−2=Θ(n)T(n)=\frac{3n}{2}-2=\Theta(n) comparisons in every case (best, average and worst).

Compared with the straightforward method that needs 2(n−1)2(n-1) comparisons, this saves about 25 percent of the comparisons, though the asymptotic order is the same. Space: the recursion depth is log⁡n\log n, so O(log⁡n)O(\log n) stack space.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

When greedy strategy provides optimal solution? Write down job sequencing with deadlines algorithm and analyze its complexity.

Answer

When greedy gives the optimal solution

A greedy strategy yields an optimal solution when the problem has both

  1. the greedy-choice property: a globally optimal solution can be built by making a locally optimal (greedy) choice at each step, and
  2. optimal substructure: an optimal solution contains optimal solutions of its subproblems.

Examples: fractional knapsack, Huffman coding, MST (Prim, Kruskal), activity selection, job sequencing with deadlines.

Job sequencing with deadlines

There are nn jobs, each takes one unit of time, and job ii has a deadline did_i and a profit pip_i earned only if it is finished by its deadline. Only one job runs at a time. The goal is to choose a feasible set of jobs and a schedule that maximises total profit.

Greedy rule: consider jobs in decreasing order of profit; place each job in the latest free slot not later than its deadline; discard it if no such slot exists.

JOB-SEQUENCING(J[1..n])        // jobs sorted so that p1 >= p2 >= ... >= pn
    d_max = max deadline
    for t = 1 to d_max: slot[t] = EMPTY
    profit = 0
    for i = 1 to n
        for t = min(d_i, d_max) downto 1
            if slot[t] is EMPTY
                slot[t] = i
                profit = profit + p_i
                break
    return slot, profit

Example. Jobs (p,d)(p,d): J1(100,2), J2(19,1), J3(27,2), J4(25,1), J5(15,3). Sorted by profit: J1, J3, J4, J2, J5. J1 goes to slot 2; J3 (deadline 2) goes to slot 1; J4 and J2 find no free slot at or before slot 1, so are rejected; J5 goes to slot 3. Schedule: J3, J1, J5 with profit 27+100+15=14227+100+15=142.

Complexity.

  • Sorting the jobs: O(nlog⁡n)O(n\log n).
  • The loop: each job scans at most dmax⁡≤nd_{\max}\le n slots, so O(n2)O(n^2) in the worst case.

Total O(n2)O(n^2) with the simple slot search. Using a disjoint-set (union-find) structure to find the latest free slot, the loop becomes almost O(n α(n))O(n\,\alpha(n)) and the total is O(nlog⁡n)O(n\log n), dominated by sorting. Space is O(n)O(n).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Suppose that a message contains alphabet frequencies as given below and find Huffman codes for each alphabet
SymbolFrequency
a30
b20
c25
d15
e35

Answer

Huffman's algorithm repeatedly merges the two nodes of smallest frequency into a new node whose frequency is their sum, until one tree remains. Left edges are labelled 0 and right edges 1.

Frequencies: a=30, b=20, c=25, d=15, e=35 (total 125).

  1. Smallest two are d(15) and b(20); merge into node N1 = 35. Remaining: a30, c25, e35, N1(35).
  2. Smallest two are c(25) and a(30); merge into N2 = 55. Remaining: e35, N1(35), N2(55).
  3. Smallest two are e(35) and N1(35); merge into N3 = 70. Remaining: N2(55), N3(70).
  4. Merge N2(55) and N3(70) into the root = 125.

Tree: root has left child N2 (c on 0, a on 1) and right child N3 (e on 0, N1 on 1); N1 has d on 0 and b on 1.

Huffman codes

SymbolFrequencyCodeLength
a30012
b201113
c25002
d151103
e35102

Total bits =30⋅2+20⋅3+25⋅2+15⋅3+35⋅2=60+60+50+45+70=285=30\cdot2+20\cdot3+25\cdot2+15\cdot3+35\cdot2=60+60+50+45+70=285, against 125⋅3=375125\cdot3=375 with a fixed 3-bit code, a saving of 24 percent. (Equal frequencies can be merged in a different order, giving a different but equally optimal set of codes.) No code is a prefix of another.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Does backtracking give multiple solution? Trace subset sum algorithm for the set {3,5,2,4,1} andd sum=8.

Answer

Does backtracking give multiple solutions?

Yes. Backtracking systematically explores the state-space tree of all candidate solutions and abandons (prunes) a partial candidate as soon as it cannot lead to a valid solution. It can be stopped at the first solution, or it can continue and report all solutions. Subset sum on the given set shows this, as there is more than one valid subset.

Subset sum. S={3,5,2,4,1}S=\{3,5,2,4,1\}, target M=8M=8. At level ii we decide to include or exclude S[i]S[i], keeping the running sum ss. We prune when s+S[i]>Ms+S[i]>M (too large) or when s+s+(sum of remaining elements) <M<M (can never reach MM).

SUBSET-SUM(i, s, chosen)
    if s == M: report chosen; return
    if i > n: return
    if s + S[i] <= M: SUBSET-SUM(i+1, s+S[i], chosen + S[i])    // include
    if s + remaining(i+1) >= M: SUBSET-SUM(i+1, s, chosen)      // exclude

Trace (include branch first):

  • Include 3, s=3s=3
    • Include 5, s=8s=8: solution {3,5}\{3,5\}.
    • Exclude 5, s=3s=3
      • Include 2, s=5s=5: including 4 gives 9 >8>8, prune; excluding 4 leaves 5+1=6<85+1=6<8, prune. Backtrack.
      • Exclude 2, s=3s=3
        • Include 4, s=7s=7
          • Include 1, s=8s=8: solution {3,4,1}\{3,4,1\}.
        • Exclude 4: 3+1=4<83+1=4<8, prune.
  • Exclude 3, s=0s=0
    • Include 5, s=5s=5
      • Include 2, s=7s=7: including 4 gives 11, prune; exclude 4, include 1 gives s=8s=8: solution {5,2,1}\{5,2,1\}.
      • Exclude 2, s=5s=5: including 4 gives 9, prune; excluding 4 leaves 6 <8<8, prune.
    • Exclude 5: remaining sum 2+4+1=7<82+4+1=7<8, prune.

Solutions found: {3,5}\{3,5\}, {3,4,1}\{3,4,1\} and {5,2,1}\{5,2,1\}. The worst case is O(2n)O(2^n), but pruning removes many branches.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Why extended euclidean algorithm is used? Write down its algorithm and analyze its complexity.

Answer

Why it is used

The Euclidean algorithm finds gcd⁡(a,b)\gcd(a,b). The extended Euclidean algorithm also finds integers x,yx,y (Bezout coefficients) such that

ax+by=gcd⁡(a,b).ax+by=\gcd(a,b).

It is used to

  • compute the modular multiplicative inverse: if gcd⁡(a,m)=1\gcd(a,m)=1 then ax+my=1ax+my=1, so a−1≡x(modm)a^{-1}\equiv x\pmod m. This is needed in RSA (computing the private exponent d=e−1 mod ϕ(n)d=e^{-1}\bmod\phi(n)) and in other cryptosystems;
  • solve linear Diophantine equations ax+by=cax+by=c and linear congruences ax≡c(modm)ax\equiv c\pmod m;
  • apply the Chinese Remainder Theorem.

Algorithm

EXTENDED-EUCLID(a, b)
    if b == 0
        return (a, 1, 0)
    (d, x1, y1) = EXTENDED-EUCLID(b, a mod b)
    x = y1
    y = x1 - floor(a / b) * y1
    return (d, x, y)

This follows from gcd⁡(a,b)=gcd⁡(b,a mod b)=bx1+(a−⌊a/b⌋b)y1\gcd(a,b)=\gcd(b,a\bmod b)=bx_1+(a-\lfloor a/b\rfloor b)y_1, which gives x=y1x=y_1 and y=x1−⌊a/b⌋y1y=x_1-\lfloor a/b\rfloor y_1.

Example. a=240a=240, b=46b=46: 240=5⋅46+10240=5\cdot46+10, 46=4⋅10+646=4\cdot10+6, 10=1⋅6+410=1\cdot6+4, 6=1⋅4+26=1\cdot4+2, 4=2⋅2+04=2\cdot2+0. So gcd⁡=2\gcd=2, and back-substituting, 2=47⋅46−9⋅2402=47\cdot46-9\cdot240 (check: 2162−2160=22162-2160=2).

Complexity

The recursion has the same steps as the Euclidean algorithm. After every two steps the remainder at least halves (and by Lame's theorem the worst case is for consecutive Fibonacci numbers). So the number of recursive calls is O(log⁡min⁡(a,b))O(\log\min(a,b)), and with constant work per call the time is O(log⁡min⁡(a,b))O(\log \min(a,b)) arithmetic operations (about O(log⁡2)O(\log^2) bit operations). The recursion depth gives O(log⁡min⁡(a,b))O(\log\min(a,b)) space (an iterative version uses O(1)O(1)).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Define NP-complete problems with examples. Give brief proof of the statement “SAT is NP-complete”.

Answer

Classes P, NP and NP-complete

  • P: decision problems solvable in polynomial time.
  • NP: decision problems whose "yes" answers can be verified in polynomial time given a certificate (a proposed solution).
  • A problem LL is NP-hard if every problem in NP can be reduced to LL in polynomial time.
  • A problem is NP-complete if it is (i) in NP and (ii) NP-hard. These are the hardest problems in NP; a polynomial algorithm for any one of them would give P=NPP=NP.

Examples: Boolean satisfiability (SAT, 3-SAT), Hamiltonian cycle, travelling salesman (decision version), vertex cover, clique, subset sum, 0/1 knapsack (decision), graph colouring.

SAT is NP-complete (Cook-Levin theorem, outline)

SAT: given a Boolean formula ϕ\phi, is there a truth assignment making it true?

1. SAT is in NP. The certificate is a truth assignment. A verifier substitutes the values into ϕ\phi and evaluates it in time linear in the size of ϕ\phi, which is polynomial.

2. SAT is NP-hard. Let LL be any language in NP. Then there is a non-deterministic Turing machine MM that decides LL in time p(n)p(n) for a polynomial pp. For an input ww of length nn, we build in polynomial time a formula ϕw\phi_w that is satisfiable if and only if MM accepts ww. The computation of MM is a p(n)×p(n)p(n)\times p(n) tableau whose rows are successive configurations (tape contents, head position, state). Boolean variables xi,j,sx_{i,j,s} say "cell (i,j)(i,j) contains symbol ss". The formula is the AND of four parts:

  • every cell contains exactly one symbol;
  • the first row is the start configuration for ww;
  • every 2×32\times3 window of cells follows a legal transition of MM;
  • some row contains the accepting state.

The formula has O(p(n)2)O(p(n)^2) variables and is built in polynomial time. ϕw\phi_w is satisfiable exactly when an accepting computation exists, so w∈L  ⟺  ϕw∈w\in L\iff\phi_w\in SAT. Thus every L∈L\in NP reduces to SAT in polynomial time.

Together, 1 and 2 show SAT is NP-complete. Other problems are then proved NP-complete by reducing a known NP-complete problem to them (e.g. SAT →\to 3-SAT →\to clique/vertex cover).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2080 · 5 marks

Write short notes on
a) Aggregate Analysis
b) Selection problems

Answer

(a) Aggregate analysis

Aggregate analysis is a method of amortized analysis. We show that for any sequence of nn operations the total worst-case cost is T(n)T(n), and then the amortized cost of each operation is T(n)/nT(n)/n, the same for all operations in the sequence, even when single operations differ in cost. It does not use probability, and it gives a tighter bound than multiplying the worst single-operation cost by nn.

Example 1: stack with MULTIPOP. PUSH, POP cost 1; MULTIPOP(kk) costs min⁡(k,size)\min(k,\text{size}). A single MULTIPOP can cost O(n)O(n), so a naive bound for nn operations is O(n2)O(n^2). But each element can be popped at most once for each time it is pushed, so total pops (including those inside MULTIPOP) ≤\le total pushes ≤n\le n. Total cost ≤2n\le 2n, amortized cost O(1)O(1) per operation.

Example 2: binary counter. In nn INCREMENT operations on a kk-bit counter, bit 0 flips every time, bit 1 every 2nd time, bit ii every 2i2^i-th time. Total flips =∑i=0k−1⌊n/2i⌋<2n=\sum_{i=0}^{k-1}\lfloor n/2^i\rfloor<2n, so the amortized cost per increment is O(1)O(1).

(b) Selection problems

The selection (order statistic) problem: given an unsorted array of nn distinct elements and an integer ii, find the ii-th smallest element. Special cases: minimum (i=1i=1), maximum (i=ni=n) and median (i=⌈n/2⌉i=\lceil n/2\rceil).

  • Sorting then indexing: O(nlog⁡n)O(n\log n).
  • Minimum or maximum: n−1n-1 comparisons, O(n)O(n).
  • Randomized-Select (quick-select): partition around a random pivot, then recurse only on the side containing the ii-th element. Expected time O(n)O(n), worst case O(n2)O(n^2).
  • Median of medians (worst-case linear selection): divide into groups of 5, take the median of each group, recursively find the median of these medians as the pivot, partition, and recurse on one side. The pivot guarantees at least about 3n/103n/10 elements on each side, giving T(n)≤T(n/5)+T(7n/10)+O(n)T(n)\le T(n/5)+T(7n/10)+O(n), which solves to O(n)O(n) in the worst case.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

What is the worst case of quick sort and how does randomize quick sort handle this problem? Sort the data { -2, 4, -3, 6, 12, 10, 11, 13, 9 } using quick sort.

Answer

Worst case of quick sort

Quick sort partitions around a pivot. The worst case occurs when the pivot is always the smallest or largest element of the sub-array, so one part has n−1n-1 elements and the other is empty. This happens, for example, when the array is already sorted (or reverse sorted) and the first or last element is chosen as pivot. Then

T(n)=T(n−1)+Θ(n) ⇒ T(n)=Θ(n2).T(n)=T(n-1)+\Theta(n)\ \Rightarrow\ T(n)=\Theta(n^2).

How randomized quick sort handles it

Randomized quick sort picks the pivot uniformly at random from the sub-array (swap a random element into the pivot position before partitioning). No particular input (such as a sorted array) can then be bad consistently, because the split depends on the random choices, not on the input order. Every pivot rank is equally likely, so the expected recurrence is

E[T(n)]=1n∑q=0n−1(E[T(q)]+E[T(n−1−q)])+Θ(n)=O(nlog⁡n).E[T(n)]=\frac1n\sum_{q=0}^{n-1}\big(E[T(q)]+E[T(n-1-q)]\big)+\Theta(n)=O(n\log n).

The worst case O(n2)O(n^2) remains possible but has very small probability.

Sorting {−2,4,−3,6,12,10,11,13,9}\{-2,4,-3,6,12,10,11,13,9\} (last element as pivot, Lomuto partition)

  1. Pivot 9: elements ≤9\le9 are −2,4,−3,6-2,4,-3,6; they move to the front, then the pivot goes after them: [−2,4,−3,6,9,10,11,13,12][-2,4,-3,6,\mathbf{9},10,11,13,12]. Left: [−2,4,−3,6][-2,4,-3,6], right: [10,11,13,12][10,11,13,12].
  2. Left [−2,4,−3,6][-2,4,-3,6], pivot 6: all others are ≤6\le6, so the pivot stays: [−2,4,−3,6][-2,4,-3,\mathbf6]. Sub-array [−2,4,−3][-2,4,-3].
  3. [−2,4,−3][-2,4,-3], pivot −3-3: none of the others is ≤−3\le-3, so swap the pivot with the first element: [−3,4,−2][\mathbf{-3},4,-2]. Sub-array [4,−2][4,-2].
  4. [4,−2][4,-2], pivot −2-2: swap: [−2,4][\mathbf{-2},4]. Done: [−3,−2,4,6][-3,-2,4,6].
  5. Right [10,11,13,12][10,11,13,12], pivot 12: 10 and 11 are ≤12\le12, 13 is not; swap 13 and 12: [10,11,12,13][10,11,\mathbf{12},13].
  6. [10,11][10,11], pivot 11: 10 ≤11\le11, no change; sorted.

Sorted output: [−3,−2,4,6,9,10,11,12,13][-3,-2,4,6,9,10,11,12,13].

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 10 marks

Does greedy algorithm guarantee optimal solution? Solve the Fractional knapsack problem to find maximum loot from given information.
Item1234567
Value121020152350
Weight (kgs)213212101

Answer

Does greedy guarantee an optimal solution?

No, not in general. A greedy algorithm gives an optimal answer only when the problem has the greedy-choice property and optimal substructure (fractional knapsack, Huffman coding, MST, activity selection). It can fail for others: 0/1 knapsack (taking items by best value/weight ratio can leave capacity unused), coin change with arbitrary denominations (denominations 1, 3, 4 and amount 6: greedy gives 4+1+1, but 3+3 is better), and travelling salesman. Each greedy algorithm needs a proof of correctness.

Fractional knapsack

The knapsack capacity is not stated in the question, so we take W=15W=15 kg. Items may be taken fractionally. Greedy rule: take items in decreasing order of value per kg.

ItemValueWeightValue/Weight
750150
210110
41527.5
32036.67
11226
63100.3
52120.167

Filling the bag in this order:

StepItem takenFractionWeight usedRemaining capacityValue gained
17111450
22121310
34141115
4317820
5119612
666/10150610×3=1.8\frac{6}{10}\times3=1.8

Total loot:

50+10+15+20+12+1.8=108.8.50+10+15+20+12+1.8=108.8.

The solution vector is x=(1,1,1,1,0,0.6,1)x=(1,1,1,1,0,0.6,1) for items 1 to 7. The same method works for any capacity WW: take whole items in ratio order until the next one does not fit, then take the fitting fraction of it. Complexity is O(nlog⁡n)O(n\log n) for the sort.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Given a set A=(5,7,10,12,15,18,20}, find the subset that sum to 35 using backtracking.

Answer

Given A={5,7,10,12,15,18,20}A=\{5,7,10,12,15,18,20\} (sorted) and target M=35M=35, we search the state-space tree, deciding at each level to include or exclude the next element while keeping the running sum ss. A node is pruned when

  • s+A[i]>Ms+A[i]>M (the element cannot be included), or
  • s+(sum of the remaining elements)<Ms+(\text{sum of the remaining elements})<M (the target can no longer be reached).

Search order (include branch first); only the branches that matter are listed:

  1. Start with 5 (s=5s=5).
    • 5, 7 (s=12s=12): adding 10 gives 22 and then 12 gives 34, and 15, 18, 20 would each overshoot; without 12, 22+15=37, 22+18=40, 22+20=42 overshoot. 5, 7, 12 gives 24, and 15, 18, 20 overshoot. 5, 7, 15 gives 27 and 5, 7, 18 gives 30, with no way to reach 35. No solution.
    • 5, 10 (s=15s=15): 5, 10, 12 gives 27, then 15, 18, 20 overshoot; 5, 10, 15 gives 30, then 18, 20 overshoot; 5, 10, 18 gives 33 and 20 overshoots; 5, 10, 20 gives 35, solution {5,10,20}\{5,10,20\}.
    • 5, 12 (s=17s=17): 5, 12, 15 gives 32 and 18, 20 overshoot; 5, 12, 18 gives 35, solution {5,12,18}\{5,12,18\}; 5, 12, 20 gives 37, prune.
    • 5, 15 gives 20, and adding 18 or 20 overshoots; 5, 18 gives 23, and adding 20 overshoots. No solution.
  2. Without 5, start with 7 (s=7s=7).
    • 7, 10 (s=17s=17): 7, 10, 12 gives 29, then everything overshoots; 7, 10, 15 gives 32, then overshoots; 7, 10, 18 gives 35, solution {7,10,18}\{7,10,18\}.
    • 7, 12 (s=19s=19): 7, 12, 15 gives 34 and nothing more fits; 7, 12, 18 gives 37, prune. 7, 15 and 7, 18 cannot reach 35. No solution.
  3. Without 5, 7, start with 10: 10+12=22, and adding 15, 18 or 20 overshoots; 10+15=25, adding 18 or 20 overshoots; 10+18=28, adding 20 overshoots. No solution.
  4. Start with 12: 12+15=27, adding 18 or 20 overshoots; 12+18=30, adding 20 overshoots. No solution.
  5. Start with 15: 15+18=33, adding 20 overshoots; 15+20=35, solution {15,20}\{15,20\}.
  6. Start with 18: 18+20=38 overshoots, so there is no solution.

Subsets with sum 35:

{5,10,20},{5,12,18},{7,10,18},{15,20}.\{5,10,20\},\quad\{5,12,18\},\quad\{7,10,18\},\quad\{15,20\}.

Check: 5+10+20=355+10+20=35, 5+12+18=355+12+18=35, 7+10+18=357+10+18=35, 15+20=3515+20=35. If only one answer is wanted, the search stops at {5,10,20}\{5,10,20\}. The worst case is O(2n)O(2^n), but pruning removes most of the tree.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Solve the following recurrence relations using master’s method.
(a)
[
T(n) = 2T\left( \frac{n}{2} \right) + n^3, \quad n > 1
]
[
T(n) = 1, \quad n = 1
]
(b)
[
T(n) = 2T\left( \frac{n}{4} \right) + 1, \quad n > 1
]
[
T(n) = 1, \quad n = 1
]

Answer

Master theorem: for T(n)=aT(n/b)+f(n)T(n)=aT(n/b)+f(n), compare f(n)f(n) with nlog⁡ban^{\log_b a}.

  1. f(n)=O(nlog⁡ba−ϵ)f(n)=O(n^{\log_b a-\epsilon}) gives T(n)=Θ(nlog⁡ba)T(n)=\Theta(n^{\log_b a}).
  2. f(n)=Θ(nlog⁡ba)f(n)=\Theta(n^{\log_b a}) gives T(n)=Θ(nlog⁡balog⁡n)T(n)=\Theta(n^{\log_b a}\log n).
  3. f(n)=Ω(nlog⁡ba+ϵ)f(n)=\Omega(n^{\log_b a+\epsilon}) and af(n/b)≤cf(n)af(n/b)\le cf(n) for some c<1c<1 gives T(n)=Θ(f(n))T(n)=\Theta(f(n)).

(a) T(n)=2T(n/2)+n3T(n)=2T(n/2)+n^3.

a=2a=2, b=2b=2, so nlog⁡22=nn^{\log_2 2}=n. Since f(n)=n3=Ω(n1+ϵ)f(n)=n^3=\Omega(n^{1+\epsilon}) with ϵ=2\epsilon=2, case 3 applies. Regularity:

2f(n/2)=2⋅n38=n34≤14f(n),2f(n/2)=2\cdot\frac{n^3}{8}=\frac{n^3}{4}\le\frac14 f(n),

so c=1/4<1c=1/4<1 holds. Therefore T(n)=Θ(n3)T(n)=\Theta(n^3).

(b) T(n)=2T(n/4)+1T(n)=2T(n/4)+1.

a=2a=2, b=4b=4, so nlog⁡42=n1/2=nn^{\log_4 2}=n^{1/2}=\sqrt n. Since f(n)=1=O(n1/2−ϵ)f(n)=1=O(n^{1/2-\epsilon}) with ϵ=1/2\epsilon=1/2, case 1 applies. Therefore

T(n)=Θ(n).T(n)=\Theta(\sqrt n).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write an algorithm to find the n^th fibonacci number with its time and space complexity.

Answer

The Fibonacci sequence is F0=0F_0=0, F1=1F_1=1, Fn=Fn−1+Fn−2F_n=F_{n-1}+F_{n-2} for n≥2n\ge2.

Iterative (dynamic programming) algorithm

FIB(n)
1   if n <= 1
2       return n
3   prev = 0
4   curr = 1
5   for i = 2 to n
6       next = prev + curr
7       prev = curr
8       curr = next
9   return curr

For n=6n=6: the values go 1, 2, 3, 5, 8, so F6=8F_6=8.

Complexity

  • Time: the loop executes n−1n-1 times with constant work in each pass, so T(n)=Θ(n)T(n)=\Theta(n) additions.
  • Space: only three variables are kept, so Θ(1)\Theta(1) auxiliary space. (Storing the whole table F[0..n]F[0..n] would use Θ(n)\Theta(n) space.)

Comparison with the plain recursive algorithm fib(n) = fib(n-1) + fib(n-2): it recomputes the same subproblems, so T(n)=T(n−1)+T(n−2)+1T(n)=T(n-1)+T(n-2)+1, which grows as Θ(ϕn)\Theta(\phi^n) with ϕ=1+52\phi=\frac{1+\sqrt5}{2} (exponential), and has O(n)O(n) stack space. Memoization reduces the time to O(n)O(n) with O(n)O(n) space. (Using fast matrix exponentiation of (1110)n\begin{pmatrix}1&1\\1&0\end{pmatrix}^n gives O(log⁡n)O(\log n) arithmetic operations.)

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Define order statistics problem. Find the edit distance between “cat” and “car” using dynamic programming.

Answer

Order statistics problem

The ii-th order statistic of a set of nn elements is the ii-th smallest element. The order statistics (selection) problem is: given an array of nn distinct numbers and an integer ii with 1≤i≤n1\le i\le n, find the element that is larger than exactly i−1i-1 other elements. The minimum is the 1st order statistic, the maximum is the nn-th and the median is the ⌈n/2⌉\lceil n/2\rceil-th. It can be solved in O(n)O(n) expected time by randomized select, or O(n)O(n) worst case by the median-of-medians algorithm, which is better than sorting in O(nlog⁡n)O(n\log n).

Edit distance between "cat" and "car"

Operations: insert, delete, substitute, each of cost 1.

D[i][j]=min⁡(D[i−1][j]+1, D[i][j−1]+1, D[i−1][j−1]+[xi≠yj])D[i][j]=\min\big(D[i-1][j]+1,\ D[i][j-1]+1,\ D[i-1][j-1]+[x_i\ne y_j]\big)

ε\varepsiloncar
ε\varepsilon0123
c1012
a2101
t3211

The last cell, D[3][3]=min⁡(D[2][3]+1, D[3][2]+1, D[2][2]+[t≠r])=min⁡(2,2,0+1)=1D[3][3]=\min(D[2][3]+1,\,D[3][2]+1,\,D[2][2]+[t\ne r])=\min(2,2,0+1)=1.

The edit distance is 1: substitute t by r.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Discuss about recursion and backtracking. Analyze the complexity of Miller Rabin Randomized Primality test.

Answer

Recursion

A recursive algorithm solves a problem by calling itself on smaller instances of the same problem until a base case is reached. It needs a base case and a recursive case that moves towards it. Examples: factorial, Fibonacci, tower of Hanoi, merge sort, binary search. Its cost is analysed with recurrence relations, and the call stack uses extra space proportional to the depth of recursion.

Backtracking

Backtracking is a systematic, depth-first search of the state-space tree of a problem. A solution is built one component at a time; if a partial solution violates a constraint (or cannot be completed), the search abandons it and returns to the previous choice to try another alternative ("prune" the subtree). It is typically implemented with recursion, where returning from a call is the backtracking step. Examples: N-Queens, subset sum, graph colouring, Hamiltonian cycle, maze solving. It avoids exploring useless candidates, though the worst case remains exponential.

Relation: backtracking is implemented naturally using recursion (the call stack stores the choices made so far), but recursion in general does not involve trying and undoing alternatives.

Miller-Rabin randomized primality test

To test an odd n>2n>2, write n−1=2sdn-1=2^s d with dd odd. For a random base a∈[2,n−2]a\in[2,n-2], nn passes the test if ad≡1(modn)a^d\equiv1\pmod n or a2rd≡−1(modn)a^{2^rd}\equiv-1\pmod n for some 0≤r<s0\le r<s. Otherwise aa is a witness that nn is composite.

MILLER-RABIN(n, k)
    write n-1 = 2^s * d
    repeat k times
        a = random(2, n-2)
        x = a^d mod n                  // fast modular exponentiation
        if x == 1 or x == n-1: continue
        repeat s-1 times
            x = x*x mod n
            if x == n-1: break
        if loop did not break: return COMPOSITE
    return PROBABLY PRIME

Complexity: with nn of β=log⁡n\beta=\log n bits, one modular exponentiation by square-and-multiply needs O(β)O(\beta) modular multiplications, each costing O(β2)O(\beta^2) bit operations with schoolbook multiplication, so one round costs O(log⁡3n)O(\log^3 n). The s−1s-1 extra squarings add only another O(log⁡3n)O(\log^3 n) at most. With kk independent rounds the total time is

O(klog⁡3n).O(k\log^3 n).

The space used is O(log⁡n)O(\log n) bits. The algorithm is one-sided: a "composite" answer is always correct, while for a composite nn at least 3/4 of the bases are witnesses, so the probability of wrongly declaring a composite number prime is at most 4−k4^{-k}. Hence a small kk (such as 20 to 40) gives negligible error in polynomial time.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Explain the approximation algorithm for vertex cover of a connected graph with an example.

Answer

Vertex cover

A vertex cover of a graph G=(V,E)G=(V,E) is a set C⊆VC \subseteq V such that every edge has at least one endpoint in CC. Finding the minimum vertex cover is NP-hard, so we use a 2-approximation algorithm.

APPROX-VERTEX-COVER(G)

  1. C←∅C \leftarrow \emptyset, E′←EE' \leftarrow E.
  2. While E′E' is not empty:
    • pick any edge (u,v)∈E′(u,v) \in E';
    • add both uu and vv to CC;
    • remove from E′E' every edge incident on uu or vv.
  3. Return CC.

Example. Take the path graph with edges (a,b),(b,c),(c,d),(d,e),(e,f)(a,b),(b,c),(c,d),(d,e),(e,f).

  • Pick (b,c)(b,c): C={b,c}C=\{b,c\}; remove (a,b),(b,c),(c,d)(a,b),(b,c),(c,d).
  • Remaining edges: (d,e),(e,f)(d,e),(e,f). Pick (d,e)(d,e): C={b,c,d,e}C=\{b,c,d,e\}; remove (d,e),(e,f)(d,e),(e,f).
  • No edges remain. Returned cover has size 4.

The optimal cover is {b,d,e}\{b,d,e\} (or {b,c,e}\{b,c,e\}) of size 3, so the algorithm gave 4, within the factor 2.

Running time. With adjacency lists, each edge is examined once, so the time is O(V+E)O(V+E).

Approximation ratio 2. The edges picked in step 2 form a matching AA (no two share an endpoint, since all edges touching a chosen edge are removed). Any vertex cover, including an optimal one C∗C^*, must contain at least one endpoint of each edge in AA, and these endpoints are distinct, so ∣C∗∣≥∣A∣|C^*| \ge |A|. The algorithm returns ∣C∣=2∣A∣|C| = 2|A|, hence

∣C∣=2∣A∣≤2∣C∗∣.|C| = 2|A| \le 2|C^*|.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

State cooks theorem. Discuss about problem reducibility.

Answer

Cook's theorem

Cook's theorem (Cook–Levin, 1971) states that the Boolean satisfiability problem (SAT) is NP-complete. That is, (i) SAT ∈\in NP, and (ii) every problem in NP is polynomial-time reducible to SAT.

Idea of the proof. SAT is in NP because a given truth assignment can be checked against the formula in polynomial time. For any language L∈L \in NP there is a non-deterministic Turing machine that decides LL in polynomial time p(n)p(n). The computation on input ww is described by a tableau of p(n)×p(n)p(n)\times p(n) cells (tape contents, state and head position at each step). A Boolean formula is built from variables saying "cell (i,j)(i,j) holds symbol ss", with clauses forcing a valid start configuration, valid moves between successive rows, and an accepting configuration. The formula has size polynomial in nn and is satisfiable exactly when the machine accepts ww. Thus L≤pL \le_p SAT.

Problem reducibility

Problem AA is polynomial-time reducible to problem BB, written A≤pBA \le_p B, if there is a function ff computable in polynomial time that maps every instance xx of AA to an instance f(x)f(x) of BB such that

x∈A  ⟺  f(x)∈B.x \in A \iff f(x) \in B.

So an algorithm for BB can solve AA: transform the input, then run the algorithm for BB.

Consequences:

  • If B∈PB \in P and A≤pBA \le_p B, then A∈PA \in P.
  • If AA is NP-hard and A≤pBA \le_p B, then BB is NP-hard. This is how new problems are proved NP-complete: show B∈B \in NP and reduce a known NP-complete problem to BB.
  • Reducibility is transitive: A≤pBA \le_p B and B≤pCB \le_p C imply A≤pCA \le_p C.

Chain of reductions starting from Cook's theorem: SAT ≤p\le_p 3-SAT ≤p\le_p Clique ≤p\le_p Vertex Cover ≤p\le_p Hamiltonian Cycle, and so on. Because SAT is NP-complete, if SAT is solved in polynomial time then P = NP.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2081 · 5 marks

Write short notes on:
a) Big Oh, Big Omega, Big theta
b) Class P, Class NP and NP-Complete

Answer

(a) Big Oh, Big Omega, Big Theta

These are asymptotic notations describing the growth of a function f(n)f(n) for large nn.

  • Big Oh (upper bound): f(n)=O(g(n))f(n) = O(g(n)) if there exist constants c>0c>0, n0≥1n_0 \ge 1 such that 0≤f(n)≤c g(n)0 \le f(n) \le c\,g(n) for all n≥n0n \ge n_0. It is used for worst-case bounds. Example: 3n+2=O(n)3n+2 = O(n) (take c=4c=4, n0=2n_0=2).
  • Big Omega (lower bound): f(n)=Ω(g(n))f(n) = \Omega(g(n)) if there exist c>0c>0, n0n_0 such that f(n)≥c g(n)≥0f(n) \ge c\,g(n) \ge 0 for all n≥n0n \ge n_0. It is used for best-case bounds. Example: 3n+2=Ω(n)3n+2 = \Omega(n).
  • Big Theta (tight bound): f(n)=Θ(g(n))f(n) = \Theta(g(n)) if there exist c1,c2>0c_1, c_2>0, n0n_0 such that c1g(n)≤f(n)≤c2g(n)c_1 g(n) \le f(n) \le c_2 g(n) for all n≥n0n \ge n_0. Equivalently f=O(g)f = O(g) and f=Ω(g)f = \Omega(g). Example: 3n+2=Θ(n)3n+2 = \Theta(n).

(b) Class P, Class NP and NP-Complete

  • Class P: decision problems solvable by a deterministic algorithm in polynomial time O(nk)O(n^k). Examples: sorting, shortest path, binary search.
  • Class NP: decision problems whose proposed solution (certificate) can be verified in polynomial time; equivalently, solvable in polynomial time by a non-deterministic machine. Examples: Hamiltonian cycle, subset sum, SAT. Clearly P⊆NPP \subseteq NP; whether P=NPP = NP is open.
  • NP-complete: a problem LL is NP-complete if (1) L∈NPL \in NP, and (2) every problem in NP reduces to LL in polynomial time (so LL is NP-hard). Examples: SAT, 3-SAT, Clique, Vertex Cover, Travelling Salesman (decision form). If any NP-complete problem is solved in polynomial time, then P=NPP = NP.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

How do you define optimal solution? Does greedy algorithm always guarantee optimal solution? Given the string “SUPER DUPER CSIT”, use a Greedy algorithm to build a Huffman tree.

Answer

Optimal solution

For an optimisation problem, a feasible solution is one that satisfies all constraints. An optimal solution is a feasible solution that gives the best value (maximum or minimum) of the objective function among all feasible solutions. There may be more than one optimal solution.

Does greedy always give the optimum?

No. A greedy algorithm builds a solution by making the locally best choice at each step and never reconsidering. It is correct only when the problem has the greedy-choice property and optimal substructure. For example, it is optimal for fractional knapsack, Huffman coding, Prim's and Kruskal's algorithms, but not for 0/1 knapsack, or for coin change with coins {1,3,4}\{1,3,4\} and amount 6 (greedy gives 4+1+14+1+1, three coins, while 3+33+3 needs two).

Huffman tree for "SUPER DUPER CSIT"

The string has 16 characters (the space counted). Frequencies:

CharSUPERspaceDCIT
Freq2222221111

Repeatedly merge the two least-frequent nodes:

  1. D(1)+C(1) →\to DC(2); I(1)+T(1) →\to IT(2).
  2. Eight nodes now have weight 2: S, U, P, E, R, space, DC, IT. Merge S+U →\to 4, P+E →\to 4, R+space →\to 4, DC+IT →\to 4.
  3. (S,U)4 + (P,E)4 →\to 8; (R,space)4 + (DC,IT)4 →\to 8.
  4. 8 + 8 →\to root 16.

Assigning 0 to the left and 1 to the right branch:

CharCodeLength
S0003
U0013
P0103
E0113
R1003
space1013
D11004
C11014
I11104
T11114

Total encoded length =6×(2×3)+4×(1×4)=36+16=52= 6\times(2\times3) + 4\times(1\times4) = 36 + 16 = 52 bits, against 16×4=6416\times 4 = 64 bits for a fixed 4-bit code (10 symbols) or 128128 bits in 8-bit ASCII. (Other tie-breaks give a different tree but the same total of 52 bits.)

Complexity. With a min-heap, nn symbols need n−1n-1 merges, each O(log⁡n)O(\log n), so O(nlog⁡n)O(n\log n).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

What is order statistics? Write and analyze the algorithm for randomized quick sort.

Answer

Order statistics

The ii-th order statistic of a set of nn elements is its ii-th smallest element. The minimum is the 1st order statistic, the maximum is the nn-th, and the median is the ⌈n/2⌉\lceil n/2 \rceil-th. It can be found by sorting in O(nlog⁡n)O(n\log n), or by the randomized select algorithm in expected O(n)O(n) time.

Randomized quick sort

Quick sort partitions the array around a pivot and sorts the two parts recursively. If the pivot is always the first or last element, a sorted input gives the worst case O(n2)O(n^2). Randomized quick sort picks the pivot uniformly at random, so no particular input is bad.

RANDOMIZED-QUICKSORT(A, p, r)
    if p < r
        q = RANDOMIZED-PARTITION(A, p, r)
        RANDOMIZED-QUICKSORT(A, p, q-1)
        RANDOMIZED-QUICKSORT(A, q+1, r)

RANDOMIZED-PARTITION(A, p, r)
    i = RANDOM(p, r)
    exchange A[r] with A[i]
    return PARTITION(A, p, r)

PARTITION(A, p, r)
    x = A[r]
    i = p - 1
    for j = p to r-1
        if A[j] <= x
            i = i + 1
            exchange A[i] with A[j]
    exchange A[i+1] with A[r]
    return i + 1

Analysis

PARTITION takes Θ(n)\Theta(n) time on nn elements.

Worst case. The pivot is the smallest or largest each time:

T(n)=T(n−1)+Θ(n)=Θ(n2).T(n) = T(n-1) + \Theta(n) = \Theta(n^2).

This happens only with probability about 2n/n!2^{n}/n! for a given input, so no input is consistently bad.

Best case. Balanced split:

T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n).T(n) = 2T(n/2) + \Theta(n) = \Theta(n\log n).

Expected case. The pivot rank qq is equally likely to be any of 1,…,n1,\dots,n:

E[T(n)]=1n∑q=1n(E[T(q−1)]+E[T(n−q)])+Θ(n)=2n∑k=0n−1E[T(k)]+Θ(n).E[T(n)] = \frac{1}{n}\sum_{q=1}^{n}\big(E[T(q-1)] + E[T(n-q)]\big) + \Theta(n) = \frac{2}{n}\sum_{k=0}^{n-1}E[T(k)] + \Theta(n).

Solving by substitution (guess E[T(k)]≤akln⁡kE[T(k)] \le ak\ln k) gives E[T(n)]=O(nlog⁡n)E[T(n)] = O(n\log n).

Alternatively, with XX the total number of comparisons, two elements zi<zjz_i < z_j are compared only if one of them is the first pivot chosen among zi,…,zjz_i,\dots,z_j, which has probability 2/(j−i+1)2/(j-i+1). Hence

E[X]=∑i<j2j−i+1<2n∑k=1n1k=O(nlog⁡n).E[X] = \sum_{i<j}\frac{2}{j-i+1} < 2n\sum_{k=1}^{n}\frac1k = O(n\log n).

Expected time is O(nlog⁡n)O(n\log n), worst case O(n2)O(n^2), extra space O(log⁡n)O(\log n) expected for the recursion stack.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 10 marks

Distinguish between dynamic programming and memorization. Parenthesize the matrices A(30 × 1), B(1 × 40), C(40 × 10) and A(10 × 15), for computing matrix multiplication using dynamic programming.

Answer

Dynamic programming vs memoization

Dynamic programming (tabulation)Memoization
Bottom-up: solves the smallest subproblems first and builds up to the answerTop-down: starts from the original problem and recurses
Fills a table iteratively in a fixed orderRecursive function with a cache; stores a result when first computed
Computes all subproblems, even those not neededComputes only the subproblems actually reached
No recursion overhead, no stack-overflow riskRecursion overhead, stack depth limit
Needs the order of subproblems worked out in advanceEasier to write directly from the recurrence

Both avoid recomputing overlapping subproblems and both give the same asymptotic time.

Matrix chain multiplication

The matrices are A1(30×1)A_1 (30\times1), A2(1×40)A_2 (1\times40), A3(40×10)A_3 (40\times10), A4(10×15)A_4 (10\times15), so the dimension array is p=⟨30,1,40,10,15⟩p = \langle 30, 1, 40, 10, 15 \rangle. With

m[i,j]=min⁡i≤k<j{m[i,k]+m[k+1,j]+pi−1pkpj}m[i,j] = \min_{i\le k<j}\{m[i,k] + m[k+1,j] + p_{i-1}p_kp_j\}

Chains of length 2:

  • m[1,2]=30⋅1⋅40=1200m[1,2] = 30\cdot1\cdot40 = 1200
  • m[2,3]=1⋅40⋅10=400m[2,3] = 1\cdot40\cdot10 = 400
  • m[3,4]=40⋅10⋅15=6000m[3,4] = 40\cdot10\cdot15 = 6000

Chains of length 3:

  • m[1,3]m[1,3]: k=1k=1: 0+400+30⋅1⋅10=7000 + 400 + 30\cdot1\cdot10 = 700; k=2k=2: 1200+0+30⋅40⋅10=132001200 + 0 + 30\cdot40\cdot10 = 13200. So m[1,3]=700m[1,3]=700, k=1k=1.
  • m[2,4]m[2,4]: k=2k=2: 0+6000+1⋅40⋅15=66000 + 6000 + 1\cdot40\cdot15 = 6600; k=3k=3: 400+0+1⋅10⋅15=550400 + 0 + 1\cdot10\cdot15 = 550. So m[2,4]=550m[2,4]=550, k=3k=3.

Chain of length 4:

  • m[1,4]m[1,4]: k=1k=1: 0+550+30⋅1⋅15=10000 + 550 + 30\cdot1\cdot15 = 1000; k=2k=2: 1200+6000+30⋅40⋅15=252001200 + 6000 + 30\cdot40\cdot15 = 25200; k=3k=3: 700+0+30⋅10⋅15=5200700 + 0 + 30\cdot10\cdot15 = 5200. So m[1,4]=1000m[1,4]=1000, k=1k=1.
i\ji\backslash j1234
1012007001000
20400550
306000
40

The split table gives s[1,4]=1s[1,4]=1, s[2,4]=3s[2,4]=3, so the optimal parenthesization is

A ((B C) D)A\,((B\,C)\,D)

with minimum cost 1000 scalar multiplications: BCBC costs 400, (BC)D(BC)D costs 150, and A×(BCD)A\times(BCD) costs 450, total 1000. The time of the algorithm is O(n3)O(n^3) and space O(n2)O(n^2).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Find the best and worst case for Bubble sort.

Answer

Bubble sort

BUBBLE-SORT(A, n)
    for i = 1 to n-1
        swapped = false
        for j = 1 to n-i
            if A[j] > A[j+1]
                exchange A[j] with A[j+1]
                swapped = true
        if swapped == false
            break

In pass ii the inner loop makes n−in-i comparisons and the largest remaining element moves to its place.

Worst case. The array is in reverse order. Every comparison causes a swap and all n−1n-1 passes run:

T(n)=(n−1)+(n−2)+⋯+1=n(n−1)2=O(n2).T(n) = (n-1) + (n-2) + \dots + 1 = \frac{n(n-1)}{2} = O(n^2).

Best case. The array is already sorted. The first pass makes n−1n-1 comparisons, no swap occurs, and the swapped flag stops the algorithm:

T(n)=n−1=Ω(n).T(n) = n-1 = \Omega(n).

(Without the flag, even the best case takes n(n−1)/2n(n-1)/2 comparisons.)

The average case is also Θ(n2)\Theta(n^2). Space is O(1)O(1) and the sort is stable.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Using Extended Euclidean Algorithm, find the GCD of 12 and 16.

Answer

Extended Euclidean Algorithm for 12 and 16

The algorithm finds gcd⁡(a,b)\gcd(a,b) and integers x,yx, y with ax+by=gcd⁡(a,b)ax + by = \gcd(a,b). Take a=12a=12, b=16b=16.

Forward steps (Euclid):

16=1⋅12+416 = 1\cdot12 + 4 12=3⋅4+012 = 3\cdot4 + 0

The last non-zero remainder is 4, so gcd⁡(12,16)=4\gcd(12,16) = 4.

Back-substitution: from the first line, 4=16−1⋅124 = 16 - 1\cdot12, i.e.

12⋅(−1)+16⋅(1)=4.12\cdot(-1) + 16\cdot(1) = 4.

So x=−1x=-1, y=1y=1.

Tabular form, with s,ts,t the coefficients of aa and bb:

qqrrsstt
1210
1601
01210
14−1-11
30

The row with remainder 4 gives −1⋅12+1⋅16=−12+16=4-1\cdot12 + 1\cdot16 = -12+16 = 4. Check: correct.

Result: gcd⁡(12,16)=4\gcd(12,16) = 4, with 4=12(−1)+16(1)4 = 12(-1) + 16(1).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Find all possible subsets of the integers that sum to 21 in the array {5, 6, 10, 11, 15} using back tracking technique.

Answer

Subset sum by backtracking

Weights (already in increasing order): w={5,6,10,11,15}w = \{5, 6, 10, 11, 15\}, target M=21M=21, total =47=47.

A state is (s,r)(s, r): ss = sum of chosen items so far, rr = sum of the remaining items. We include the next item wkw_k only if s+wk≤Ms + w_k \le M, and explore further only if s+r≥Ms + r \ge M. Otherwise we prune (backtrack).

Exploring the state-space tree (left branch = include, right = exclude):

  • Include 5, s=5s=5:
    • Include 6, s=11s=11:
      • Include 10, s=21s=21: solution {5,6,10}\{5,6,10\}.
      • Exclude 10: include 11 gives 22 > 21, pruned; exclude 11: include 15 gives 26, pruned.
    • Exclude 6, s=5s=5, r=36r=36:
      • Include 10, s=15s=15: 11 gives 26 and 15 gives 30, both pruned.
      • Exclude 10: include 11, s=16s=16; 15 gives 31, pruned; without 15, s+r=16<21s+r=16<21, pruned. Exclude 11: s+r=5+15=20<21s+r = 5+15 = 20 < 21, pruned.
  • Exclude 5, s=0s=0:
    • Include 6, s=6s=6:
      • Include 10, s=16s=16: 11 gives 27, pruned; without 11, 15 gives 31, pruned; 16<2116<21 otherwise.
      • Exclude 10: include 11, s=17s=17: 15 gives 32, pruned, and 17<2117<21. Exclude 11: s+r=6+15=21s + r = 6+15 = 21, include 15: s=21s=21, solution {6,15}\{6,15\}.
    • Exclude 6, s=0s=0, r=36r=36:
      • Include 10, s=10s=10: include 11, s=21s=21: solution {10,11}\{10,11\}. Exclude 11: 15 gives 25, pruned.
      • Exclude 10: r=26r=26; include 11, s=11s=11, 15 gives 26, pruned, and 11<2111<21. Exclude 11: r=15<21r=15<21, pruned.

All subsets summing to 21:

{5,6,10},{6,15},{10,11}\{5,6,10\},\quad \{6,15\},\quad \{10,11\}

Check: 5+6+10=215+6+10=21, 6+15=216+15=21, 10+11=2110+11=21. The worst-case time is O(2n)O(2^n), but pruning removes most of the tree.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Define class P and NP problem. Why do we need approximation algorithms? Justify.

Answer

Class P

The set of decision problems that can be solved by a deterministic algorithm in polynomial time, O(nk)O(n^k) for some constant kk. Examples: searching, sorting, shortest paths, minimum spanning tree.

Class NP

The set of decision problems for which a given solution (certificate) can be verified in polynomial time; equivalently, problems solvable in polynomial time by a non-deterministic algorithm. Examples: Hamiltonian cycle, subset sum, SAT, graph colouring. Every problem in P is in NP (P⊆NPP \subseteq NP); whether P=NPP = NP is unsolved.

Why approximation algorithms are needed

  • Many important optimisation problems (travelling salesman, vertex cover, set cover, bin packing, knapsack) are NP-hard. No polynomial-time exact algorithm is known, and one probably does not exist unless P=NPP=NP.
  • Exact algorithms (brute force, branch and bound) take exponential time, which is useless for large inputs: for n=100n=100, 21002^{100} steps are impossible in practice.
  • An approximation algorithm runs in polynomial time and returns a solution that is provably close to the optimum, with approximation ratio ρ\rho such that C≤ρ C∗C \le \rho\,C^* (for minimisation), where CC is the cost found and C∗C^* the optimal cost.
  • Example: the matching-based vertex cover algorithm runs in O(V+E)O(V+E) and always returns a cover at most twice the minimum size.
  • Such a guaranteed, fast, near-optimal answer is more useful in practice than an exact answer that never arrives. Heuristics give no such guarantee.

Hence approximation algorithms give a practical trade-off between solution quality and running time for NP-hard problems.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

State the time and space complexity for sequential search. Write the rules for master theorem for finding asymptotic bounds.

Answer

Sequential (linear) search

It compares the key with each element in turn until a match is found or the array ends.

Time complexity

  • Best case: the key is the first element, 1 comparison, O(1)O(1).
  • Worst case: the key is last or absent, nn comparisons, O(n)O(n).
  • Average case: about (n+1)/2(n+1)/2 comparisons, O(n)O(n).

Space complexity: O(1)O(1), since only a loop index and a few variables are used.

Master theorem

For a recurrence of the form

T(n)=a T(n/b)+f(n),a≥1, b>1,T(n) = a\,T(n/b) + f(n),\qquad a\ge1,\ b>1,

with f(n)f(n) asymptotically positive, compare f(n)f(n) with nlog⁡ban^{\log_b a}:

  1. Case 1: if f(n)=O(nlog⁡ba−ϵ)f(n) = O(n^{\log_b a - \epsilon}) for some ϵ>0\epsilon>0, then T(n)=Θ(nlog⁡ba)T(n) = \Theta(n^{\log_b a}).
  2. Case 2: if f(n)=Θ(nlog⁡ba)f(n) = \Theta(n^{\log_b a}), then T(n)=Θ(nlog⁡balog⁡n)T(n) = \Theta(n^{\log_b a}\log n).
  3. Case 3: if f(n)=Ω(nlog⁡ba+ϵ)f(n) = \Omega(n^{\log_b a + \epsilon}) for some ϵ>0\epsilon>0 and af(n/b)≤cf(n)a f(n/b) \le c f(n) for some constant c<1c<1 (regularity), then T(n)=Θ(f(n))T(n) = \Theta(f(n)).

Example: T(n)=2T(n/2)+nT(n) = 2T(n/2) + n has nlog⁡22=n=f(n)n^{\log_2 2} = n = f(n), so case 2 gives Θ(nlog⁡n)\Theta(n\log n).

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Justify the worst case for binary search. Find the edit distance from the string “RELEVANT” to “ELEPHANT” using dynamic programming approach.

Answer

Worst case of binary search

Binary search on a sorted array of nn elements compares the key with the middle element and discards half of the array each time. The worst case occurs when the key is absent or is found only when one element remains. The recurrence is

T(n)=T(n/2)+1,T(1)=1.T(n) = T(n/2) + 1,\quad T(1)=1.

After kk steps the size is n/2kn/2^k; the search ends when n/2k=1n/2^k = 1, i.e. k=log⁡2nk = \log_2 n. So the worst-case number of comparisons is ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1, which is O(log⁡n)O(\log n) (the best case is 1 comparison, O(1)O(1)). For example, n=1024n=1024 needs at most 11 comparisons.

Edit distance from RELEVANT to ELEPHANT

Operations: insert, delete, substitute, each of cost 1. Let D[i,j]D[i,j] be the distance between the first ii letters of RELEVANT and the first jj letters of ELEPHANT:

D[i,j]=min⁡{D[i−1,j]+1, D[i,j−1]+1, D[i−1,j−1]+[ai≠bj]}D[i,j] = \min\{D[i-1,j]+1,\ D[i,j-1]+1,\ D[i-1,j-1] + [a_i \ne b_j]\}

with D[i,0]=iD[i,0]=i, D[0,j]=jD[0,j]=j.

ELEPHANT
012345678
R112345678
E212234567
L321234567
E432123456
V543223456
A654333345
N765444434
T876555543

The edit distance is D[8,8]=3D[8,8] = \mathbf{3}.

Tracing back: delete R, keep E, L, E, substitute V by P, insert H, keep A, N, T. That is one deletion, one substitution and one insertion, 3 operations in all. The algorithm runs in O(mn)O(mn) time and space.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

  • 2082 · 5 marks

Distinguish between recursion and backtracking. Using Miller-Rabin primality test, check whether 53 is prime or not?

Answer

Recursion vs backtracking

RecursionBacktracking
A function calls itself on a smaller instance of the same problemA systematic search that builds a solution step by step and abandons a partial solution that cannot lead to a valid one
A programming technique that can be used for any problem (factorial, Fibonacci, merge sort)An algorithm design technique for constraint/search problems (N-queens, subset sum, graph colouring)
Needs a base case to stopStops on a solution or when all candidates are tried; uses a bounding or feasibility test to prune
Does not undo choicesUndoes the last choice ("backtracks") and tries the next alternative
Backtracking is usually implemented using recursion, but recursion need not backtrack

Miller–Rabin test for n=53n=53

Write n−1=52=2rdn-1 = 52 = 2^r d with dd odd: 52=22⋅1352 = 2^2\cdot13, so r=2r=2, d=13d=13.

Pick the witness a=2a=2 and compute x=ad mod nx = a^d \bmod n:

26=64≡11,212≡112=121≡15,213≡30(mod53).2^{6} = 64 \equiv 11,\quad 2^{12} \equiv 11^2 = 121 \equiv 15,\quad 2^{13} \equiv 30 \pmod{53}.

So x0=30x_0 = 30, which is neither 1 nor n−1=52n-1 = 52. Square it:

x1=302=900=16⋅53+52≡52=n−1(mod53).x_1 = 30^2 = 900 = 16\cdot53 + 52 \equiv 52 = n-1 \pmod{53}.

We reach n−1n-1, so 5353 passes the test for a=2a=2 (it is "probably prime").

Check with a=3a=3: 34=81≡283^4 = 81 \equiv 28, 38≡282=784≡423^8 \equiv 28^2 = 784 \equiv 42, 312≡42⋅28=1176≡103^{12} \equiv 42\cdot28 = 1176 \equiv 10, 313≡303^{13} \equiv 30; squaring gives 5252 again, so it passes as well.

Since 53 passes for both bases (and 53 has no divisor up to 53≈7.3\sqrt{53}\approx7.3: not divisible by 2, 3, 5 or 7), 53 is prime.

Answer checked by Claude Sonnet · Oct 21, 2026

Test yourself · 2 MCQs

Loading…

Questions from TU BSc CSIT 2076 Cryptography (TU IOST board exam, 2076), TU BSc CSIT 2078 Cryptography (TU IOST board exam, 2078), TU BSc CSIT 2079 Cryptography (TU IOST board exam, 2079), TU BSc CSIT 2080 Cryptography (TU IOST board exam, 2080), TU BSc CSIT 2081 Cryptography (TU IOST board exam, 2081), TU BSc CSIT 2082 Cryptography (TU IOST board exam, 2082), TU BSc CSIT 2076 Design and Analysis of Algorithms (TU IOST board exam, 2076), TU BSc CSIT 2078 Design and Analysis of Algorithms (TU IOST board exam, 2078), TU BSc CSIT 2079 Design and Analysis of Algorithms (TU IOST board exam, 2079), TU BSc CSIT 2080 Design and Analysis of Algorithms (TU IOST board exam, 2080), TU BSc CSIT 2081 Design and Analysis of Algorithms (TU IOST board exam, 2081), TU BSc CSIT 2082 Design and Analysis of Algorithms (TU IOST board exam, 2082), TU BSc CSIT 2080 Image Processing (TU IOST board exam, 2080), TU BSc CSIT 2081 Image Processing (TU IOST board exam, 2081), TU BSc CSIT 2082 Image Processing (TU IOST board exam, 2082), TU BSc CSIT 2080 Multimedia Computing (TU IOST board exam, 2080), TU BSc CSIT 2081 Multimedia Computing (TU IOST board exam, 2081), TU BSc CSIT 2082 Multimedia Computing (TU IOST board exam, 2082), TU BSc CSIT 2076 System Analysis and Design (TU IOST board exam, 2076), TU BSc CSIT 2078 System Analysis and Design (TU IOST board exam, 2078), TU BSc CSIT 2079 System Analysis and Design (TU IOST board exam, 2079), TU BSc CSIT 2080 System Analysis and Design (TU IOST board exam, 2080), TU BSc CSIT 2081 System Analysis and Design (TU IOST board exam, 2081), TU BSc CSIT 2082 System Analysis and Design (TU IOST board exam, 2082), TU BSc CSIT 2076 Society and Ethics in Information Technology (TU IOST board exam, 2076), TU BSc CSIT 2078 Society and Ethics in Information Technology (TU IOST board exam, 2078), TU BSc CSIT 2079 Society and Ethics in Information Technology (TU IOST board exam, 2079), TU BSc CSIT 2076 Simulation and Modeling (TU IOST board exam, 2076), TU BSc CSIT 2078 Simulation and Modeling (TU IOST board exam, 2078), TU BSc CSIT 2079 Simulation and Modeling (TU IOST board exam, 2079), TU BSc CSIT 2080 Simulation and Modeling (TU IOST board exam, 2080), TU BSc CSIT 2081 Simulation and Modeling (TU IOST board exam, 2081), TU BSc CSIT 2082 Simulation and Modeling (TU IOST board exam, 2082), TU BSc CSIT 2076 Web Technology (TU IOST board exam, 2076), TU BSc CSIT 2078 Web Technology (TU IOST board exam, 2078), TU BSc CSIT 2079 Web Technology (TU IOST board exam, 2079), TU BSc CSIT 2080 Web Technology (TU IOST board exam, 2080), TU BSc CSIT 2081 Web Technology (TU IOST board exam, 2081) and TU BSc CSIT 2082 Web Technology (TU IOST board exam, 2082). Answers are written for this site; check them against your class notes.