✅ Explained - Simple and Clear Python3 Code✅
Intuition\nThe problem requires calculating the sum of distances between all pairs of robots after a given command is executed. To solve this, we can simulate t
# Intuition\nThe problem requires calculating the sum of distances between all pairs of robots after a given command is executed. To solve this, we can simulate the movement of the robots and keep track of their positions. Whenever two robots collide, they will change their directions and continue moving. We need to calculate the sum of distances between all pairs of robots at a specific time point.\n\n\n# Approach\nThe approach begins by updating the positions of the robots based on the given command string \'s\' and the time \'d\'. If the command is \'L\', the robot at index \'i\' will move \'d\' units to the left (subtracting \'d\' from its position in the \'nums\' array). If the command is \'R\', the robot will move \'d\' units to the right (adding \'d\' to its position). This step ensures that the positions of the robots reflect their movement after the command is executed.\n\nNext, the algorithm initializes the answer variable \'ans\' to 0. It then sorts the \'nums\' array in ascending order. The variable \'s\' is used to keep track of the cumulative sum of robot positions.\n\nIn the subsequent loop, the algorithm iterates over the \'nums\' array. For each robot at index \'i\', it calculates the distance between that robot and all robots to its left. The distance is given by \'nums[i] * i - s\'. The algorithm adds this distance to \'ans\' and takes the modulo \'mod\' to prevent the answer from becoming too large.\n\nAdditionally, the algorithm updates the value of \'s\' by adding \'nums[i]\' to it and takes the modulo \'mod\'. This ensures that \'s\' represents the cumulative sum of robot positions up to the current index \'i\'.\n\nFinally, the algorithm returns \'ans\' modulo \'mod\', which gives us the desired sum of distances between all pairs of robots after \'d\' seconds.\n\n\n\n\n\n\n# Code\n```\nclass Solution:\n    def sumDistance(self, nums: List[int], s: str, d: int) -> int:\n        for i in range(len(s)):\n            if s[i] == \'L\':\n                nums[i] -= d\n            else:\n                nums[i] += d\n                \n        ans = 0\n        nums.sort()\n        mod = 10 ** 9 + 7\n        s = 0\n        \n        for i in range(len(nums)):\n            ans += (nums[i] * i - s)\n            ans %= mod\n            s += nums[i]\n            s %= mod\n        \n        return ans % mod\n```
['Python3']