ProgrammingHardInfosys · Cognizant
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 is P[r] - P[l-1]. What is printed for the range l = 2, r = 5?
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 is P[r] - P[l-1]. What is printed for the range l = 2, r = 5?
P[0] = 0 for k = 1 to 6: P[k] = P[k-1] + a[k] Print P[5] - P[1]
- A. 12
- B. 11
- C. 13
- D. 21
Correct answer: C. 13
The sum from position 2 to position 5 is 1 + 7 + 3 + 2 = 13, which equals P[5] - P[1]. Subtracting P[2] drops one element, stopping at P[4] drops the last one, and reading P[6] adds an extra element.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- 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…
- Array a = [1, 2, 3, 4, 5, 6, 7] is rotated to the right by k = 3 positions: each element moves k places to the right with wrap-around. The…
- Lomuto partition is applied to a = [3, 8, 2, 5, 1, 4] with the pivot equal to the last element. For j = 0 to n - 2: if a[j] <= pivot, then…
- For the array a = [2, 9, 4, 7, 5, 6, 3] (indices 0 to 6), the procedure below computes the sum of the maximum values of all contiguous…
- Array a = [3, 1, 4, 1, 5, 9, 2, 6] is scanned from left to right. The procedure below counts the positions i (from 2 to n) where a[i] is…
- Array a = [5, 3, 8, 1] (length 4). The procedure below counts how many elements are leaders, where an element is a leader if it is…