ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer printed = 0
Procedure perm(String s, Integer l)      // s is passed by value
    if (l == length(s) - 1)
        printed = printed + 1
        return
    end if
    for (each i from l to length(s) - 1)
        swap(s[l], s[i])
        perm(s, l + 1)
        swap(s[l], s[i])
    end for
End Procedure
perm("AAB", 0)
Print printed
  1. A. 6
  2. B. 3
  3. C. 2
  4. D. 9

Correct answer: A. 6

Without a check for repeated letters, the swap method produces all 3! = 6 orders, treating the two A's as different, so AAB, ABA and BAA each appear twice. printed = 6 although only 3 strings are distinct.

More Pseudocode and Code Tracing questions

Exams that ask this topic