ProgrammingVery hardTCS NQT · Accenture
Array a = [3, 4, 1, 2, 4, 2, 1, 3] and target K = 7. The procedure below counts contiguous subarrays whose sum is exactly K, using prefix sums and a count of earlier prefixes. What is printed?
Array a = [3, 4, 1, 2, 4, 2, 1, 3] and target K = 7. The procedure below counts contiguous subarrays whose sum is exactly K, using prefix sums and a count of earlier prefixes. What is printed?
P = 0; count = 0; seen[0] = 1
for each element x in a
P = P + x
count = count + seen[P - K]
seen[P] = seen[P] + 1
end for
Print count- A. 19
- B. 4
- C. 1
- D. 2
Correct answer: B. 4
The prefix sums are 3, 7, 8, 10, 14, 16, 17, 20, and counting earlier prefixes that differ from the current one by exactly 7 gives 4 subarrays. Counting subarrays with sum at most 7 gives 19, counting adjacent pairs that sum to 7 gives 1, and counting subarrays that sum to 14 gives 2.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Insertion sort on the array [5, 2, 4, 6, 1, 3] shifts an element one place right each time it moves past a larger element. The procedure…
- Array a = [3, 8, 7, 2, 7]. A linear scan returns the 0-based index of the first occurrence of 7. What is printed? for i = 0 to n - 1 if…
- Binary search for the value 13 in the sorted array [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] uses lo = 0, hi = n - 1 and mid = (lo + hi) div 2…
- Array a = [8, 4, 2, 1, 7, 5]. The number of inversions (pairs i < j with a[i] > a[j]) is the number of out-of-order pairs, and merge sort…
- Prefix sums are computed for a = [4, 1, 7, 3, 2, 8] with P[0] = 0 and P[k] = a[1] + ... + a[k]. A range sum for 1-based positions l to r…
- Array a = [4, 1, 7, 3, 2, 8] (three queries are not needed here). The procedure below counts the elements that are strictly greater than…