ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (+ joins strings)

What will be the output of the following pseudocode? (+ joins strings)
Integer count = 0
String third = ""
Procedure gen(String s, Integer open, Integer close, Integer n)
    if (length(s) == 2 * n)
        count = count + 1
        if (count == 3) third = s
        return
    end if
    if (open < n) gen(s + "x", open + 1, close, n)       // x = opening bracket
    if (close < open) gen(s + "y", open, close + 1, n)  // y = closing bracket
End Procedure
gen("", 0, 0, 3)
Print count, third
  1. A. 5 xxyxyy
  2. B. 5 xxyyxy
  3. C. 6 xxyyxy
  4. D. 5 xyxxyy

Correct answer: B. 5 xxyyxy

The recursion builds every balanced string of 3 pairs, always trying x (open) before y (close): xxxyyy, xxyxyy, xxyyxy, xyxxyy, xyxyxy, i.e. ((())), (()()), (())(), ()(()), ()()(). count = 5 (a Catalan number) and the third is xxyyxy.

More Pseudocode and Code Tracing questions

Exams that ask this topic