Java | 100% faster |  Two Pass with explanation
First let\'s look at the O(N^2) solution - \nSimply do a double iteration and for each ball found, compute the distance and add it to the cost. Easy peasy.\n\nc
First let\'s look at the O(N^2) solution - \nSimply do a double iteration and for each ball found, compute the distance and add it to the cost. Easy peasy.\n```\nclass Solution {\n    public int[] minOperations(String boxes) {\n        int len = boxes.length();\n        int[] ans = new int[len];\n        for(int i=0;i<len;i++){\n            int cost = 0;\n            for(int j=0;j<len;j++){\n                if(boxes.charAt(j)==\'1\') cost += Math.abs(i-j);\n            }\n            ans[i] = cost;\n        }\n        return ans;\n    }\n}\n```\n\nNow, let\'s take a look at the O(N) solution. The code has two passes, forward and back. \nThe assumption is when we travel forward we\'re only considering the balls that are left to the current index, similarly when we travel back we\'re only considering the balls that are to the right of the current index.\nWhen moving forward, the cost of moving balls to the right for ith index can be computed if we know the total number of balls till (i-1)th index and the cost of moving balls till (i-1)th index i.e\n*forward[i] = forward[i-1]+number_of_balls_till_i-1*\nIn a similar fashion, \n*back[i] = back[i+1]+number_of_balls_till_i+1*\n\nOnce we have both these values, the answer is simply the summation of the forward and backward costs.\n```\nclass Solution {\n    public int[] minOperations(String boxes) {\n        int len = boxes.length();\n        int[] forward = new int[len];\n        int prev = (boxes.charAt(0)==\'0\'?0:1);\n        for(int i=1;i<len;i++){\n            forward[i] += forward[i-1]+prev;\n            prev += (boxes.charAt(i)==\'0\'?0:1);\n        }\n        prev = (boxes.charAt(len-1)==\'0\'?0:1);\n        int[] back = new int[len];\n        for(int i=len-2;i>=0;i--){\n            back[i] += back[i+1]+prev;\n            prev += (boxes.charAt(i)==\'0\'?0:1);\n        }\n        int[] op = new int[len];\n        for(int i=0;i<len;i++) op[i] = forward[i]+back[i];\n        return op;\n    }\n}\n```
['Java']