call(back)
Algorithms & Data StructuresmediumSign in to star problems

Earliest Block Removal That Balances the Array

You are given an integer array nums and an integer k with 1 <= k <= nums.length. Delete one block of k consecutive elements. The remaining elements close up and are re-indexed from zero.

The result is balanced when the sum of its even-indexed elements equals the sum of its odd-indexed elements (an empty array is balanced). Return the smallest starting index of a block whose removal leaves a balanced array, or -1 if no block does.

earliestBalancedRemoval([2, 1, 6, 4], 1)  ->  1   // [2, 6, 4]: 2 + 4 = 6
earliestBalancedRemoval([1, 2, 3], 2)     ->  -1

Up to 200,000 elements; values may be negative. Checking every block from scratch is too slow.

Hints

Hint 1

Work with one number instead of two: the even-indexed sum minus the odd-indexed sum. Balanced means that difference is zero.

Hint 2

Elements before the block keep their index. Elements after it move left by k, so their parity flips exactly when k is odd.

Hint 3

Precompute B[t], the even-minus-odd difference of the first t elements. The suffix after the block contributes B[n] - B[l + k], negated when k is odd.

Topics

Asked at

Similar Problems6