ProgrammingModerateTCS NQT · Accenture
The procedure below finds the smallest 0-based index i at which the prefix sum of [4, -1, 3, -2, 5] reaches at least 7. It prints i. What is printed?
The procedure below finds the smallest 0-based index i at which the prefix sum of [4, -1, 3, -2, 5] reaches at least 7. It prints i. What is printed?
s = 0
for i = 0 to n - 1
s = s + a[i]
if s >= 7 then print i; stop
end for- A. 2
- B. 5
- C. 4
- D. 3
Correct answer: C. 4
Prefix sums are 4, 3, 6, 4 and 9, so the first index reaching 7 is index 4 (value 9). Using a threshold of 6 stops at index 2, the 1-based index is 5, and the index of the minimum element is 3.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Two sorted arrays a = [1, 4, 7] and b = [2, 3, 8, 9] are merged by the two-pointer procedure below, and the procedure prints the 4th…
- The procedure below repeatedly replaces x by the sum of its decimal digits, starting from x = 2^15, until x is a single digit, and prints…
- An array holds the values [3, 0, 2, 0, 1] (positions 0 to 4). The procedure below computes the water trapped above each position as…
- The Fibonacci sequence 1, 1, 2, 3, 5, ... is generated by the loop below, and the procedure prints how many terms are less than or equal…
- The string "aabcccdddd" is compressed by the procedure below, which replaces each run of equal letters by the letter followed by the run…
- The procedure below scans the word "leetcode" from the left and prints the index of the first letter that occurs exactly once in the word…