ProgrammingVery hardProduct company OA

After the call below, what is c?

After the call below, what is c?
int c = 0;
void perm(char *s, int k, int n) {
    if (k == n) { c++; return; }
    for (int i = k; i < n; i++) {
        if (i != k && s[i] == s[k]) continue;
        char t = s[k]; s[k] = s[i]; s[i] = t;
        perm(s, k + 1, n);
        t = s[k]; s[k] = s[i]; s[i] = t;
    }
}
/* in main: */ char s[] = "AAB"; perm(s, 0, 3);
  1. A. 6
  2. B. 2
  3. C. 3
  4. D. 4

Correct answer: C. 3

Without the skip line this would generate all 3! = 6 orderings. The skip refuses to swap a character into position k if it equals the one already there, so the duplicate A–A swap at the top level is skipped: the branches are AAB → {AAB, ABA} and BAA → {BAA}. That is 3, the number of distinct arrangements of AAB.

More C Programming questions

Exams that ask this topic