ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode? (s[i] - '0' turns a digit character into its value; strings are indexed from 0)
What will be the output of the following pseudocode? (s[i] - '0' turns a digit character into its value; strings are indexed from 0)
String s = "1226"
Integer dp[0..4]
dp[0] = 1
dp[1] = 1
for (each i from 2 to 4)
dp[i] = 0
if (s[i - 1] != '0')
dp[i] = dp[i] + dp[i - 1]
end if
Integer two = (s[i - 2] - '0') * 10 + (s[i - 1] - '0')
if (two >= 10 AND two <= 26)
dp[i] = dp[i] + dp[i - 2]
end if
end for
Print dp[4]- A. 5
- B. 3
- C. 4
- D. 8
Correct answer: A. 5
dp[i] counts ways to read the first i digits as letters (1 = A, …, 26 = Z). 1226 splits as 1|2|2|6, 12|2|6, 1|22|6, 1|2|26, 12|26: dp = 1, 1, 2, 3, 5, so the output is 5.
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? (+ joins strings) Integer count = 0 String third = "" Procedure gen(String s, Integer…
- 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…