Understand Minimum Number of Operations to Move All Balls to Each Box Problem

Problem Name: Minimum Number of Operations to Move All Balls to Each Box
Problem Description:

Problem: Minimum Number of Operations to Move All Balls to Each Box

You have n boxes represented as a binary string boxes, where:

  • '0' means the box is empty.
  • '1' means the box contains one ball.

You can move a ball from one box to an adjacent box in one operation. A box is adjacent if the difference in their indices is 1.

You need to calculate an array answer of size n where:

  • answer[i] is the minimum number of operations required to move all balls to the ith box, considering the initial positions of the balls.

Examples

Example 1:

Input:
boxes = "110"
Output:
[1, 1, 3]

Boxes

The number of operations required to move all balls to the 0th index box from the initial state = 1.

Boxes

The number of operations required to move all balls to the 1st index box from the initial state = 1.

Boxes

The number of operations required to move all balls to the 3rd index box from the initial state = 2.

Boxes

The total number of operations required to move all balls to each index box from the initial state is given by the array:

ans = [1, 1, 3]

Explanation:

  1. For the first box: Move one ball from the second box → 1 operation.
  2. For the second box: Move one ball from the first box → 1 operation.
  3. For the third box:
    • Move one ball from the first box → 2 operations.
    • Move one ball from the second box → 1 operation.
      Total = 3 operations.

Example 2:

Input:
boxes = "001011"
Output:
[11, 8, 5, 4, 3, 4]


Constraints

n=boxes.lengthn = \text{boxes.length} 1n20001 \leq n \leq 2000 boxes[i]{0,1}\text{boxes}[i] \in \{ 0 , 1 \}
Category:
  • Leetcode Problem of the Day
  • Arrays
  • Strings
Programming Language:
  • Java
Reference Link:

https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/description/?envType=daily-question&envId=2025-01-06

Online IDE

Scroll down for output
Java
Output:

Loading component...

Loading component...

Tracking code (View only. In case you want to track the code, click this button):
Main Function:

Main Function is not defined.

Helper Function:

INPUT: boxes = "110"

OUTPUT: [1, 1, 3]

public static int[] minOperations(String boxes) {

int n = boxes.length();

int[] distances = new int[n];

int prefixCount = 0;

int prefixSum = 0;

for( int i = 0; i < n ; i++){

distances[i] = prefixCount * i - prefixSum;

if(boxes.charAt(i) == '1'){

++prefixCount;

prefixsum += i;

}//If End

}//Loop End

int suffixCount = 0;

int suffixSum = 0;

for(int i = n-1; i >= 0; --i) {

distances[i] += suffixSum - suffixCount * i;

if ( boxes.charAt(i) == '1' ) {

++suffixCount;

suffixSum += i;

}//If End

}//Loop End

return distances;

}//function end

Utility Functions and Global variables:

Utility Function is not required.