ProgrammingHardTCS NQT · Accenture
For the array a = [1, 2, 3, 4, 5, 6], the procedure below counts the contiguous subarrays of length 3 whose sum is divisible by 3. What is printed?
For the array a = [1, 2, 3, 4, 5, 6], the procedure below counts the contiguous subarrays of length 3 whose sum is divisible by 3. What is printed?
count = 0
for i = 0 to n - 3
if (a[i] + a[i+1] + a[i+2]) mod 3 == 0 then count = count + 1
end for
Print count- A. 0
- B. 4
- C. 2
- D. 6
Correct answer: B. 4
The window sums are 6, 9, 12 and 15, all divisible by 3, so the count is 4. Counting the windows that are not divisible gives 0, using pairs gives a different count, and wrapping around the array adds windows.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Two numbers are formed from the arrays a = [1, 3, 5] and b = [2, 3, 6] by merging them into one sorted list. The procedure below prints…
- For the array a = [-1, 4, -2, 6, -3, 5], the procedure below finds the maximum sum of a contiguous window of exactly 3 elements (windows…
- Array a = [4, 9, 2, 8, 2, 7]. The procedure below counts the prefix records, that is, the positions i where a[i] is strictly greater than…
- A rotated sorted array a = [4, 5, 6, 7, 0, 1, 2] has its smallest element at some index. The procedure below finds that index by a linear…
- The loops below print the pairs (i, j) with 1 <= i <= j <= 3 in order, and the procedure prints the total count of pairs. What is printed?…
- Array a = [3, 1, 2]. The procedure below performs a stable count of the number of ways the array can be read in increasing order using…