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]
  1. A. 5
  2. B. 3
  3. C. 4
  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.

More Pseudocode and Code Tracing questions

Exams that ask this topic