Kotlin O(nlogn) sort + prefix sum (with comment)
Code\n\nclass Solution {\n    fun sumDistance(nums: IntArray, s: String, d: Int): Int {\n        val mod = 1000000007\n\n        /*\n         * Ignore direction
# Code\n```\nclass Solution {\n    fun sumDistance(nums: IntArray, s: String, d: Int): Int {\n        val mod = 1000000007\n\n        /*\n         * Ignore direction changes, since we don\'t need to track robots, and if a robot x and\n         * a robot y meet, and change directions we can look at it as if the two robots continued\n         * on the same path/direction without changing direction. Keep long array to avoid Integer overflow\n         */\n        val afterMove = LongArray (nums.size).apply {\n            for (i in 0 until nums.size) {\n                if (s[i] == \'L\') this[i] = (nums[i] - d).toLong()\n                else this[i] = (nums[i] + d).toLong()\n            }\n        }\n        \n        // sort the robot positions in order to calculate the sum\n        // of the distances of all robots in one sweep below\n        afterMove.sort()\n\n        /*\n         * To avoid comparing all pairs of (i, j) and calculate in O(n^2),\n         * we use a prefix sum to calculate this in O(n) + sorting of O(nlogn)\n         */\n        var res = 0L\n        var prefix = 0L\n        for (i in 1 until afterMove.size) {\n            prefix += i * (afterMove[i] - afterMove[i - 1])\n            res = (res + prefix) % mod\n        }\n\n        return res.toInt()\n    }\n}\n```
['Kotlin']