ProgrammingVery hardGoldman Sachs OA · Amazon OA

What will be the output of the following pseudocode? (strings are indexed from 0)

What will be the output of the following pseudocode? (strings are indexed from 0)
Procedure perm(String s, Integer l)        // s is passed by value (a copy)
    if (l == length(s) - 1)
        Print s
        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("ABC", 0)
  1. A. ABC ACB BAC BCA CAB CBA
  2. B. ABC ACB BCA BAC CAB CBA
  3. C. ABC ACB BAC BCA CBA CAB
  4. D. ABC BAC CBA ACB BCA CAB

Correct answer: C. ABC ACB BAC BCA CBA CAB

Swap-based generation fixes each letter at the front in turn. Putting C in front swaps A and C, giving CBA, and its sub-call prints CBA then CAB. So the order is ABC ACB BAC BCA CBA CAB — not dictionary order at the end.

More Pseudocode and Code Tracing questions

Exams that ask this topic