🤯 99.59% fast linear time python solution | Easiest | Explained
Logic is to calculate the sum of indices having balls and store it in ans[0]. We also calculate number of balls that are ahead of index 0 as we iterate once.\n\
Logic is to calculate the sum of indices having balls and store it in ans[0]. We also calculate number of balls that are ahead of index 0 as we iterate once.\n\nAs you iterate forward again, reduce the previous sum (at index - 1 in the ans array) by the number of balls ahead and increase the previous sum by number of balls behind. \n\nSince when you move ahead, **the distance from balls behind increases by 1 for every ball behind current index but the distance from balls ahead decreases by 1 for every ball ahead of current index.**\n\nUpvote if you understood the logic :)\n\n```\nclass Solution:\n    def minOperations(self, boxes: str) -> List[int]:\n        \n        ans = [0] * len(boxes)\n        sumAhead = ballsAhead = ballsBehind = 0\n               \n        for i in range(1, len(boxes)):\n            if boxes[i] == \'1\':\n                sumAhead += i\n                ballsAhead += 1\n        \n        ans[0] = sumAhead\n        \n        if boxes[0] == \'1\':\n            ballsBehind += 1\n        \n        for i in range(1, len(ans)):\n            ans[i] = ans[i - 1] + ballsBehind - ballsAhead\n            \n            if boxes[i] == \'1\':\n                ballsBehind += 1\n                ballsAhead -= 1\n            \n        return ans  \n```\n
['Array', 'Python']