ProgrammingHardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Integer count = 0
String last = ""
Procedure gen(String s, Integer n)
    if (length(s) == n)
        count = count + 1
        last = s
        return
    end if
    gen(s + "0", n)
    if (length(s) == 0 OR s[length(s) - 1] == '0')
        gen(s + "1", n)
    end if
End Procedure
gen("", 4)
Print count, last
  1. A. 16 1111
  2. B. 5 1010
  3. C. 8 1010
  4. D. 8 0101

Correct answer: C. 8 1010

gen builds binary strings of length 4 with no two adjacent 1's, trying 0 before 1, so they come out in increasing order: 0000, 0001, 0010, 0100, 0101, 1000, 1001, 1010. count = 8 and the last one is 1010.

More Pseudocode and Code Tracing questions

Exams that ask this topic