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- A. 5 xxyxyy
- B. 5 xxyyxy
- C. 6 xxyyxy
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer s = 0 for (each i from 1 to 49) if (i mod 3 == 0 OR i mod 5 == 0) s = s + i…
- What will be the output of the following pseudocode? (| is OR, & is AND, << and >> are shifts) Integer c = 0, r, x for (each n from 1 to…
- What will be the output of the following pseudocode? Function iso(String a, String b) Map f = empty, g = empty for (each i from 0 to…
- What will be the output of the following pseudocode? (strings are indexed from 0) String s = "AEBCBDA" String t = reverse of s Integer n =…
- What will be the output of the following pseudocode? Integer p[6] = {7, 1, 5, 3, 6, 4} Integer lo = p[0], one = 0, many = 0 for (each i…
- What will be the output of the following pseudocode? (Arrays are indexed from 0) Integer a[5] = {2, 3, 1, 1, 4} Integer jumps = 0, curEnd…