Similar Problems
Similar Problems not available
Minimum Number Of Operations To Move All Balls To Each Box - Leetcode Solution
Companies:
LeetCode: Minimum Number Of Operations To Move All Balls To Each Box Leetcode Solution
Difficulty: Medium
Problem:
You have n boxes. You are given a string boxes of length n, where boxes[i] is one of '0', '1', or '2'.
You want to move all the balls to the rightmost box. Each box i, numbered from 0 to n - 1, can contain at most one ball.
You can perform the following operations any number of times:
- Move one ball from a box to an adjacent box.
- Move one ball from box i to box j if they are both empty.
Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.
Each answer[i] is calculated considering the initial state of the boxes.
Solution:
We can solve this problem by iterating over the string boxes and for each box we can calculate the number of operations required to move all the balls to that box.
To do this, let's first iterate over the string and count the number of balls to the right of each box. We will also keep track of the total number of balls in the string.
We can then iterate over the string again and calculate the number of operations required to move all the balls to each box.
For each box, we can calculate the number of operations required by first calculating the number of balls to the left and to the right of the box. We can then multiply these values to get the total number of operations required.
Let's write the code to implement this solution.
Code:
def minOperations(boxes): # Count the number of balls to the right of each box num_balls_to_right = [0] * len(boxes) total_balls = 0 for i in range(len(boxes)-1, -1, -1): if boxes[i] == '1': total_balls += 1 num_balls_to_right[i] = total_balls
# Calculate the number of operations required for each box
res = [0] * len(boxes)
for i in range(len(boxes)):
num_balls_to_left = i - sum(1 for j in range(i) if boxes[j] == '1')
num_balls_to_right = num_balls_to_right[i]
res[i] = num_balls_to_left * num_balls_to_left + num_balls_to_right * num_balls_to_right
return res
Time Complexity:
The time complexity of this solution is O(n^2), because we are iterating over the string twice and for each box we are iterating over the string again to calculate the number of balls to the left.
Space Complexity:
The space complexity of this solution is O(n), because we are creating two extra lists of size n to store the number of balls to the right and the result.
Minimum Number Of Operations To Move All Balls To Each Box Solution Code
1