KatInterview

Balance Point Count in a Weighted Sensor Array

Arrays & HashingAuto-graded · 17 test cases
MediumAuto-gradedArrays & Hashingarraysprefix sumshash maps

Last updated

Tests the ability to use prefix sums to efficiently count indices where the weighted sum to the left equals the weighted sum to the right.

Balance Point Count in a Weighted Sensor Array

A sensor array records integer readings. Given the readings and a positive integer weight w, define the weighted left sum at index i as:

w * (readings[0] + readings[1] + ... + readings[i-1])

and the weighted right sum at index i as:

readings[i+1] + readings[i+2] + ... + readings[n-1]

Note that the left side is multiplied by w but the right side is not.

Index i is called a balance point if its weighted left sum equals its weighted right sum.
For i = 0, the weighted left sum is 0 (empty product).
For i = n-1, the weighted right sum is 0 (empty sum).

Return the count of balance points across all indices.

Constraints

  • 1 <= len(readings) <= 2000
  • -10^4 <= readings[i] <= 10^4
  • 1 <= w <= 100
  • An array of length 1 always has exactly 1 balance point (index 0).

Examples

Example 1

Input: count_balance_points([2, 3, 1, 6, 2], 2)

Output: 0

Example 2

Input: count_balance_points([1, -1, 1, -1, 1], 1)

Output: 5

Example 3

Input: count_balance_points([5], 7)

Output: 1

Hints

Hint 1

Compute the total sum of the array first; then think about how you can express the right sum at index i in terms of a running prefix sum you maintain as you scan left to right.

Hint 2

At index i, right_sum = total_sum - prefix_sum - readings[i], where prefix_sum is the sum of all elements before i. The balance condition becomes w * prefix_sum == right_sum.

Hint 3

No extra data structure beyond a running sum is needed — the check is O(1) per index, giving an O(n) overall solution.