Minimum Number of Operations to Move All Balls to Each Box

medium prefix sum two passes

Problem

There are n boxes in a row, described by a binary string boxes: boxes[i] is '1' if box i starts with exactly one ball and '0' if it is empty. One operation moves a single ball from its box into an adjacent box (one step left or right).

For every index i, compute the minimum number of operations needed to bring all the balls into box i, with each computation restarting from the original configuration. Return the n results as an array.

Inputboxes = "110"
Output[1, 1, 3]
Gathering both balls into box 0 takes 1 move (the ball in box 1 steps left); box 1 likewise takes 1; box 2 needs 2 + 1 = 3 moves.

def min_operations(boxes):
    n = len(boxes)
    answer = [0] * n
    balls = ops = 0
    for i in range(n):
        answer[i] += ops
        balls += int(boxes[i])
        ops += balls
    balls = ops = 0
    for i in range(n - 1, -1, -1):
        answer[i] += ops
        balls += int(boxes[i])
        ops += balls
    return answer
function minOperations(boxes) {
  const n = boxes.length;
  const answer = new Array(n).fill(0);
  let balls = 0, ops = 0;
  for (let i = 0; i < n; i++) {
    answer[i] += ops;
    balls += boxes[i] === "1" ? 1 : 0;
    ops += balls;
  }
  balls = 0; ops = 0;
  for (let i = n - 1; i >= 0; i--) {
    answer[i] += ops;
    balls += boxes[i] === "1" ? 1 : 0;
    ops += balls;
  }
  return answer;
}
int[] minOperations(String boxes) {
    int n = boxes.length();
    int[] answer = new int[n];
    int balls = 0, ops = 0;
    for (int i = 0; i < n; i++) {
        answer[i] += ops;
        balls += boxes.charAt(i) - '0';
        ops += balls;
    }
    balls = 0; ops = 0;
    for (int i = n - 1; i >= 0; i--) {
        answer[i] += ops;
        balls += boxes.charAt(i) - '0';
        ops += balls;
    }
    return answer;
}
vector<int> minOperations(string boxes) {
    int n = boxes.size();
    vector<int> answer(n, 0);
    int balls = 0, ops = 0;
    for (int i = 0; i < n; i++) {
        answer[i] += ops;
        balls += boxes[i] - '0';
        ops += balls;
    }
    balls = 0; ops = 0;
    for (int i = n - 1; i >= 0; i--) {
        answer[i] += ops;
        balls += boxes[i] - '0';
        ops += balls;
    }
    return answer;
}
Time: O(n) Space: O(1) extra