Chapter 3: Recursion, Binary Search and Backtracking

Data Structures and Algorithms with C · Study Questions
Base case and frameTail recursionBinary searchTowers of HanoiPermutationSAT and subsetn-queensWarnsdorff
Sercan KÜLCÜ · Giresun University · Computer Engineering

Classic Question · Recursion

Question 1: An Unreachable Base Case

What does the function below return for f(5)? What is the bug, and how is it fixed?

int f(int n) {
  if (n == 0)
    return 0;
  return n + f(n - 2);
}
Show answer

The calls go n = 5, 3, 1, −1, −3, …; since n is odd, it never becomes 0. The base case is never reached, every call opens a new frame, and the program crashes with a stack overflow; f(5) returns no value.

Every call must get closer to the base case and be able to reach it. Fix: if (n <= 0) return 0; → f(5) = 5 + 3 + 1 = 9. f(4) would have worked in the old version too (4 + 2 + 0 = 6); so the bug shows up only for some inputs, and the test data must be varied.

Multiple Choice · Recursion

Question 2: A Tail Call

In which of the return lines below is the recursive call a tail call?

C: In a tail call the result of the call is returned as it is; no work remains after the return. In A, B and D the returned value must be multiplied or added to, so the frame is kept. In C the partial result is carried in the acc parameter; the compiler can turn this call into a jump and run it with O(1) stack.

Step-by-Step Trace · Recursion

Question 3: Printing Before and After

show(3): what does it print? Which frames are on the stack each time printf runs?

n = 3 ≠ 0: first 3 is printed, then show(2) is called.

The new frame has its own n: 2 is printed.

1 is printed, show(0) is called.

Base case: show(0) returns without printing anything. The stack is at its deepest (4 show frames).

show(1) resumes where it left off: the second printf prints 1, and the frame closes.

The second printf of show(2): 2.

Output 3 2 1 1 2 3. The work before the call is done in descent order, the work after it in return order (reversed).

void show(int n) {
  if (n == 0) return;
  printf("%d ", n);
  show(n - 1);
  printf("%d ", n);
}
/* main: show(3); */

Multiple Choice · Binary Search

Question 4: Middle Indices

Test array {4, 13, 18, 19, 24, 27, 33, 36, 39, 40}. The iterative binsearch(list, 40, 0, 9) tries which middle indices, in order?

A: (0 + 9)/2 = 4 → 24 < 40, left = 5; (5 + 9)/2 = 7 → 36 < 40, left = 8; (8 + 9)/2 = 8 → 39 < 40, left = 9; (9 + 9)/2 = 9 → found. 4 rounds, consistent with at most ⌊log₂ 10⌋ + 1 = 4. Integer division rounds down; D rounds the first middle up (4.5 → 5).

Spot the Bug · Binary Search

Question 5: The Range Does Not Shrink

binsearch: in this version + 1 and - 1 have been forgotten. What happens when 4 and 40 are searched in the test array?

while (left <= right) {
  int middle = (left + right) / 2;
  switch (COMPARE(list[middle], searchnum)) {
    case -1: left = middle; break;
    case 0: return middle;
    case 1: right = middle;
  }
}
return -1;
Show answer
  • 4: the middle indices are 4, 2, 1, 0 → list[0] = 4 is found, 0 is returned. The bug does not show on this input.
  • 40: 4 → left = 4; 6 → left = 6; 7 → left = 7; 8 → left = 8. Then with left = 8, right = 9, middle = 8, list[8] = 39 < 40 → left = middle gives 8 again. The range never shrinks: an infinite loop.

middle has already been checked, so it must be removed from the range: left = middle + 1, right = middle - 1. Only then does every round shrink the range by at least one, and the loop ends in at most ⌊log₂ n⌋ + 1 rounds.

Multiple Choice · Binary Search

Question 6: The Forgotten return

In the recursive binsearch, the return before the two recursive calls has been forgotten. On the test array, what does binsearch(list, 18, 0, 9) return?

switch (COMPARE(list[m], x)) {
  case -1: binsearch(list, x, m + 1, r);
           break;
  case 0:  return m;
  case 1:  binsearch(list, x, l, m - 1);
           break;
}
return -1;

B: In the first call m = 4, list[4] = 24 > 18 → binsearch(list, 18, 0, 3) runs and finds 2, but the returned value is thrown away; after break the return -1 on the last line runs. Only the value found at the first middle (24 → 4) is returned correctly. The code compiles; it may not even warn.

Classic Question · Binary Search

Question 7: At Most How Many Rounds?

How many rounds does the iterative binsearch run at most on a sorted array? Find it for n = 2000, n = 4095 and n = 4096. Does the count change if the searched value is not in the array?

Show answer

At most ⌊log₂ n⌋ + 1 rounds:

n200040954096
⌊log₂ n⌋101112
max rounds111213

4095 = 2¹² − 1 elements form a decision tree with exactly 12 levels; one more element adds a round. If the value is absent, the range still halves every round and left > right occurs after at most the same number of rounds (for n = 2000, 11 was found by trying all possible values).

Step-by-Step Trace · Towers of Hanoi

Question 8: Hanoi with Base Case n = 0

In this version, whose base case is n == 0, what does hanoi(2, 'A', 'B', 'C') print? How many times is the function called in total?

ABC21

n = 2: first the top disk 1 from A to B (C is the helper).

ABC21

hanoi(1, A, C, B): first hanoi(0, A, B, C).

ABC21

Base case: returns without doing anything. The stack is deepest: 3 hanoi frames.

ABC21

Disk 1: A → B. Then hanoi(0, C, A, B) is called and returns at once.

ABC12

The largest disk 2: A → C.

ABC21

hanoi(1, B, A, C): hanoi(0, B, C, A) returns, disk 1: B → C.

ABC21

The last hanoi(0, A, B, C) returns too. 3 moves but 7 calls: moves 2ⁿ − 1, calls 2ⁿ⁺¹ − 1. For n = 10: 1023 moves, 2047 calls.

void hanoi(int n, char src, char aux, char dst) {
  if (n == 0) return;          /* base case */
  hanoi(n - 1, src, dst, aux);
  printf("%c -> %c\n", src, dst);
  hanoi(n - 1, aux, src, dst);
}
/* main: hanoi(2, 'A', 'B', 'C'); */

Classic Question · Towers of Hanoi

Question 9: Moves with Four Disks

The hanoi(4, "A", "B", "C") call from the slides: what is move 5? In which move is the largest disk (4) moved? How many times does the smallest disk change place?

Show answer

Moves: 1: A→B, 2: A→C, 3: B→C, 4: A→B, 5: C→A (disk 1), 6: C→B, 7: A→B, 8: A→C (disk 4), 9: B→C, …, 15: B→C.

  • The largest disk moves right after the 3 disks on top of it have been moved to the middle peg, in the 2³ − 1 + 1 = 8th move.
  • Disk 1 moves in every odd-numbered move: 8 of the 15 moves. In general, disk k is moved 2n−k times: 8 + 4 + 2 + 1 = 15 = 2⁴ − 1.

Since n = 4 is even, the first move goes to the middle peg (B), not to the target.

Multiple Choice · Permutation

Question 10: Number of Calls in Permutation

The swap-based perm(list, 0, 4) call, for "abcd", makes how many perm calls in total, itself included?

D: At level i there are n(n−1)…(n−i+1) calls: 1 + 4 + 12 + 24 + 24 = 65. The last term, i = n, is the leaf calls; each prints one arrangement. A counts only the leaves (4! = 24); C skips the leaf level (i = n). Time is O(n·n!), with n characters per leaf.

Output Question · Permutation

Question 11: If the Swap Back Is Forgotten

perm: the second SWAP has been deleted. What does perm("abc", 0, 3) print? What is the array after the call?

void perm(char *list, int i, int n) {
  int j, temp;
  if (i == n) {
    for (j = 0; j < n; j++)
      printf("%c", list[j]);
    printf(" ");
  } else
    for (j = i; j < n; j++) {
      SWAP(list[i], list[j], temp);
      perm(list, i + 1, n);
    }
}
Show answer

Output: abc acb cab cba abc acb, and at the end the array is acb.

  • At level i = 1 the branches j = 1, 2 print abc and acb; the array stays acb.
  • i = 0, j = 1: in acb, list[0] ↔ list[1] → cab; the sub-branches print cab, cba, and the array stays cba.
  • i = 0, j = 2: list[0] ↔ list[2] → abc; abc, acb again.

Sibling branches do not see the same starting array, so abc and acb appear twice; bac and bca never appear. Swapping back means undoing the choice.

Multiple Choice · Backtracking

Question 12: Satisfying Assignments

How many assignments satisfy the formula (x1 ∨ x2) ∧ ¬x3 ∧ (¬x1 ∨ x3) (2³ assignments are tried)?

D: ¬x3 requires x3 = 0. Then ¬x1 ∨ x3 holds only with x1 = 0, and x1 ∨ x2 then needs x2 = 1. The only assignment is x1x2x3 = 010. A backtracking search that assigns x3 first would prune the x3 = 1 branch at once by the clause ¬x3 and never try 4 assignments to the end.

Step-by-Step Trace · Backtracking

Question 13: Subset Sum with Pruning

search(0, 0) prints the subsets with sum 7 in which order? Which branches are pruned?

a[]pick[]5·3·2·4·sum = 0

search(0, 0): 5 is taken → search(1, 5).

a[]pick[]51312·4·sum = 8

Taking 3 too gives sum = 8 > 7: the branch is pruned; 2 and 4 are never tried in this branch.

a[]pick[]5130214·sum = 7

3 is not taken, 2 is taken: sum = 7 = T → the solution 5 2 is printed.

a[]pick[]51302040sum = 5

5 + 4 = 9 is pruned; 5 alone returns without a result at i == N.

a[]pick[]50312·4·sum = 3

The root moves to its right branch: 5 is not taken, 3 is taken.

a[]pick[]50312041sum = 7

3 + 2 + 4 = 9 is pruned; with 2 not taken, 3 + 4 = 7 → the solution 3 4.

a[]pick[]50302040sum = 0

No sum of 7 is reachable in the branch without 5 and 3 (2, 4). 23 calls; 29 without pruning. When a solution is printed, only the decisions with j < i count.

int a[] = {5, 3, 2, 4}, pick[4];
int N = 4, T = 7;
void search(int i, int sum) {
  int j;
  if (sum == T) {                /* solution */
    for (j = 0; j < i; j++)
      if (pick[j]) printf("%d ", a[j]);
    printf("\n");
    return;
  }
  if (i == N || sum > T) return; /* prune */
  pick[i] = 1; search(i + 1, sum + a[i]);
  pick[i] = 0; search(i + 1, sum);
}

Multiple Choice · Backtracking

Question 14: Six Queens

In the 6-queens problem, q = [1, 3, 5] has been placed in the first three rows. For which columns c does safe(3, c) return 1?

C: Columns 1, 3, 5 are occupied. c = 0: with q[2] = 5, |5 − 0| = 5 ≠ 1; with q[1] = 3, 3 ≠ 2; with q[0] = 1, 1 ≠ 3 → safe. c = 2: |5 − 2| = 3 ≠ 1, |3 − 2| = 1 ≠ 2, |1 − 2| = 1 ≠ 3 → safe. c = 4: |5 − 4| = 1 = 3 − 2 → diagonal threat. Continuing from 0 finds the solution [1, 3, 5, 0, 2, 4].

Coding Question · Backtracking

Question 15: Counting All Solutions

The safe function is given. Write a function that counts all solutions of the n-queens problem: int count(int r, int n). How does it differ from place? What does count(0, 6) return?

Show answer
int count(int r, int n) {
  int c, total = 0;
  if (r == n) return 1;       /* one solution */
  for (c = 0; c < n; c++)
    if (safe(r, c)) {
      q[r] = c;
      total += count(r + 1, n);  /* keep going */
    }
  return total;
}

place stops at the first solution: return 1 ends all the calls; count instead sums the returned numbers and continues the loop. q[r] is not undone, because the next attempt overwrites it and safe looks only at rows i < r.

Results: n = 4 → 2, n = 5 → 10, n = 6 → 4, n = 8 → 92.

Multiple Choice · Backtracking

Question 16: Warnsdorff's Rule

In a knight's tour, how does Warnsdorff's rule choose the next square for the knight?

B: Squares with few options (corners, edges) are used up first, so a dead end is not left for later. The rule looks at only 8 neighbors per step and does O(n²) work in total, but gives no guarantee of a solution. D is backtracking: it always solves it, but is very slow on 8 × 8. A spends the easy squares instead of leaving them for the end.

The End

Chapter 3: Recursion, Binary Search and Backtracking: Study Questions
Lecture slides: Chapter 3: Recursion, Binary Search and Backtracking · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.