Data Structures & AlgorithmsVery hard
Why is prefix-sum counting of zero-sum subarrays unaffected by the choice of starting index for the prefix array?
- A. Prefix sums always start at zero by definition, so the count changes with the start.
- B. A subarray sum is the difference of two prefix sums, so the starting constant cancels out in every comparison.
- C. The difference of two prefix sums is always zero.
- D. Only the last prefix sum is used by the algorithm.
Correct answer: B. A subarray sum is the difference of two prefix sums, so the starting constant cancels out in every comparison.
Adding a constant to every prefix sum leaves all differences unchanged, so equal-prefix pairs are the same. This is why an empty prefix of zero is the natural seed.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- For the sum-at-most-K problem on a prefix-sum array with negative values, why does a balanced search structure appear in the solution?
- The shunting-yard algorithm converts the infix expression "a+bc^d^e-f^(gh)" to postfix, with ^ highest precedence and right-associative…
- What is the largest rectangular area in a histogram with bar heights 6, 2, 5, 4, 5, 1, 6 (each bar has width 1)?
- In the undirected graph with edges (1,2), (1,3), (2,4), (3,4), (4,5), (3,6), how many vertices are at shortest-path distance exactly 2…
- What is the minimum number of knight moves needed to go from square (0, 0) to (3, 3) on an 8 by 8 board (coordinates 0 to 7)?
- Two sorted linked lists are [1, 5, 9, 12] and [2, 3, 8]. They are merged into one sorted list. What is the 5th value of the merged list…