Problem Description
Given a binary string where each character represents a box (with '1' indicating the presence of a ball and '0' for empty), determine an output array where each element at index i is the minimum number of operations needed to move all balls from their original positions to box i. In one operation, a ball can move to an adjacent box (i.e., from index j to j-1 or j+1).
Key Insights
- For any target box, the cost is the sum of the absolute distances from every other box that contains a ball.
- A naive approach would loop through each target box and each ball, leading to O(n^2) time complexity.
- By performing two passes (one from the left and one from the right), we can efficiently calculate the cumulative operations required for each box in O(n) time.
- In the left-to-right pass, keep track of the number of balls encountered so far and the cumulative cost needed to shift balls one position right.
- Similarly, the right-to-left pass accumulates the cost of shifting balls left.
- Combining both pass results in the desired answer.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) (for the output array)
Solution
The solution uses a two-pass approach:
- First, traverse from left to right. As you move, maintain a counter of balls encountered (left_count) and a running cost (left_ops) which represents the cumulative moves required for all balls to reach that point. Assign left_ops to the answer array at each index before updating.
- Next, traverse from right to left with similar logic using right_count and right_ops. Accumulate the cost in the answer array.
- This results in each answer index containing the sum of operations needed from both directions to gather all balls at that index.
This approach avoids recalculating distances from scratch for each index by maintaining cumulative information, serving as a dynamic programming technique applied in two directions.