ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer a[5] = {1, 2, 3, 4, 5}
Integer odd = 0, even = 1, s = 0, ans = 0 // counts of prefix sums by parity
for (each i from 0 to 4)
s = s + a[i]
if (s mod 2 == 1)
ans = ans + even
odd = odd + 1
else
ans = ans + odd
even = even + 1
end if
end for
Print ans- A. 15
- B. 9
- C. 6
- D. 10
Correct answer: B. 9
A subarray has an odd sum when its two bounding prefix sums have different parity. Prefix sums 0, 1, 3, 6, 10, 15 have parities E, O, O, E, E, O: 3 odd and 3 even, so 3 × 3 = 9 subarrays have an odd sum.
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 32-bit integers) Function pow4(Integer n) return n > 0 AND (n &…
- What will be the output of the following pseudocode? (& is AND, ^ is XOR, << is left shift) Integer x = 7, m = 1 while ((x & m) != 0) x =…
- What will be the output of the following pseudocode? Integer printed = 0 Procedure perm(String s, Integer l) // s is passed by value if (l…
- What will be the output of the following pseudocode? Integer t[4][4] = {{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}} // row r has r + 1 numbers…
- What will be the output of the following pseudocode? Integer a = 20, b = 6, c = 0 while (a > b) a = a - 3 b = b + 2 c = c + 1 end while…
- What will be the output of the following pseudocode? Integer r[3][4] = {{1, 2, 3, 4}, {2, 4, 6, 8}, {4, 2, 5, 1}} Integer c = 0 for (each…