Java | O(n) | LTR * 2
This solution relies on updating counters for the balls that we have seen so far as we travel from left to right. As we get further away from balls on the left,
This solution relies on updating counters for the balls that we have seen so far as we travel from left to right. As we get further away from balls on the left, the number of operations needed scales positively linearly with the number of balls we\'ve seen. Similarly, for the balls on the right of our current box, the number of operations scales negatively linearly with the number of balls we\'ve seen. Therefore, to start off the algorithm, we need to count all of the balls to the right of the \'0\'th box. \n\nOnce we know how many balls are to the right, we just update our counters on each iteration. This is similar to the LTR + RTL approaches that are heavily voted up in the discussion, but the second pass traverses from the left.\n```\n    public int[] minOperations(String boxes) {\n        // Initialize the number of operations and our counters\n        int[] numberOfOperations = new int[boxes.length()];\n        int ballsToTheLeft = 0, ballsInBox = boxes.charAt(0) - \'0\', ballsToTheRight = 0;\n        // Calculate how many operations are required to move all balls to the first bin\n        for (int i = 1; i < numberOfOperations.length; i++) {\n            int ball = boxes.charAt(i) - \'0\';\n            ballsToTheRight += ball;\n            numberOfOperations[0] += i * ball;\n        }\n        // Count how many operations are required for the rest of the bins. This relies on where the balls are in relation to the current box;\n        for (int i = 1; i < numberOfOperations.length; i++) {\n            int ball = boxes.charAt(i) - \'0\';\n            // As we move to the right, update our counters based on positions of the seen balls\n            ballsToTheLeft += ballsInBox;\n            ballsInBox = ball;\n            ballsToTheRight -= ballsInBox;\n            // We rely on the previous box operations as our base count\n            // We subtract the balls to the right and in the current bucket since we\'re moving towards them\n            // We add the balls to the left because we\'re moving away from them\n            numberOfOperations[i] = numberOfOperations[i - 1] - ballsToTheRight - ballsInBox + ballsToTheLeft;\n        }\n        return numberOfOperations;\n    }\n
['Java']