ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
What will be the output of the following pseudocode? (All variables are integers, so / is integer division)
Integer dp[0..10]
dp[1] = 0
for (each i from 2 to 10)
dp[i] = dp[i - 1] + 1
if (i mod 2 == 0) dp[i] = min(dp[i], dp[i / 2] + 1)
if (i mod 3 == 0) dp[i] = min(dp[i], dp[i / 3] + 1)
end for
Print dp[10]- A. 4
- B. 2
- C. 5
- D. 3
Correct answer: D. 3
dp[i] is the fewest steps to reach 1 using −1, ÷2, ÷3. The best path for 10 is 10 → 9 → 3 → 1 (3 steps). Halving first, as a greedy rule would, gives 10 → 5 → 4 → 2 → 1 (4 steps).
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? (& is bitwise AND on two's-complement integers) Integer c = 0 for (each i from 0 to…
- What will be the output of the following pseudocode? (^ is XOR, & is AND; x & (−x) keeps the lowest 1-bit) Integer a[6] = {2, 4, 7, 9, 2…
- What will be the output of the following pseudocode? String w[3] = {"flower", "flow", "flight"} String p = w[0] for (each i from 1 to 2)…
- What will be the output of the following pseudocode? (substring(s, i, 2) is the 2 characters from index i; sorted(t) puts t's letters in…
- What will be the output of the following pseudocode? (strings are indexed from 0) String p = "ABABCABAB" Integer f[9], k = 0 f[0] = 0 for…
- What will be the output of the following pseudocode? Integer a[4] = {1, 2, 3, 4}, res[4], left = 1, right = 1 for (each i from 0 to 3)…