There are N buckets arranged in a row. Each bucket either is empty or contains a ball. The buckets are specified as a string buckets consisting of characters "." (empty bucket) and " B " (bucket with aball). For example, for buckets = "B. BB. B. . B" the row of buckets appears as follows: In one move you can take the ball out of any bucket and place it in another (empty) bucket. Your goal is to arrange the balls to create an alternating sequence of full and empty buckets. In other words, the distance between two consecutive balls should be equal to 2. Note that the sequence may start at any bucket. For example, in the figure below, the balls are placed correctly: On the other hand, in both of the figures below, the balls are placed incorrectly: What is the minimum number of moves required to create a correct sequence of balls in buckets
Replits:
I also failed this interview question and it took me a long time to finally understand the solution.
For anyone struggling with unemployment, you should study sliding window algorithms.
In this case, the correct "textbook" solution for this problem is a fixed-sized sliding window algorithm.
The code above fails some of my test cases because it assumes that the minimum solution is always to move the balls towards the left. However, in cases like
B.............................B.Bthe minimum solution is 1, not 2.That's why we need to slide the window (
arranged_balls) rather than just zip it to one spot.I made a longer explanation here:
https://gist.github.com/MarcAbonce/f442dc85796f1bd4481f8c85dacb31a8