KatInterview

Balanced Alternating Sums After One Removal

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingprefix-sumsparityarray

Last updated

Count positions whose removal makes the sum at even positions equal the sum at odd positions, testing prefix/suffix sums and the parity shift after a deletion.

You are given a list of integers values. Positions are numbered from 0.

Suppose you remove exactly one element, at position p. Every element that was to the right of p moves one place to the left, so the positions in the shortened list are renumbered from 0.

Call the shortened list balanced if the sum of its elements at even positions equals the sum of its elements at odd positions. An empty list has both sums equal to 0, so it is balanced.

Return the number of positions p (each considered independently, on the original list) for which removing the element at p produces a balanced list.

Each removal is evaluated separately on the original list. Different positions count separately even if they hold equal values.

Constraints

  • 0 <= len(values) <= 10^5
  • Values are integers and may be zero or negative; the sums fit in a standard 64-bit integer.
  • An empty input returns 0.
  • A single-element list returns 1, since removing that element leaves an empty, balanced list.

Examples

Example 1

Input: count_balanced_removals([2, 1, 6, 4])

Output: 1

Example 2

Input: count_balanced_removals([1, 1, 1])

Output: 3

Example 3

Input: count_balanced_removals([1, 2, 3])

Output: 0

Hints

Hint 1

Elements before the removed position keep their positions. Elements after it shift left by one, so their even/odd roles swap.

Hint 2

After removing position p, the even-position sum is (even-position sum of the left part) + (odd-position sum of the original right part), and similarly for the odd-position sum.

Hint 3

Start with the total even and odd sums, then sweep left to right. Subtract the current element from its parity total before testing, and add it to the left accumulators only after testing.