C++ || Simple || Easily Understandable || Faster
Intuition\n Describe your first thoughts on how to solve this problem. \n- As given that certain index value moves in certain direction.\n- Upon collision of tw
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- As given that certain index value moves in certain direction.\n- Upon collision of two values they change their direction and start moving in opposite direction.\n- By this we can understand that when two balls collide they change their direction. So consider that if two balls collide and they pass through each other without changing their direction will also have cause of action.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Simply add d to the index which are moving in \'R\' direction.\n- Subtract d from the indexes which are moving in \'L\' direction.\n- Sort the array\n- Then find the distance between every pair with the help of prefix sum in O(1) time.\n\n# Complexity\n- Time complexity: O(NLogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O{N}\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int sumDistance(vector<int>& nums, string s, int d) {\n        int n = s.length();\n        int m = 1e9+7;\n        for(int i = 0 ; i< n; i++){\n            if(s[i] == \'R\')\n            nums[i] += d;\n            else\n            nums[i] -= d;\n        }\n        sort(nums.begin(), nums.end());\n        vector<int> pre;\n        long long sum = 0;\n        for(auto i : nums)\n        {\n            sum = (sum + i)%m;\n            pre.push_back(sum);\n        }\n        \n        long long ans = 0 ;\n        for(int i = 0 ; i< n - 1; i++){\n            ans = (ans + ((sum - pre[i] + m)%m - ((n-i-1)*1ll*(nums[i]))%m +m)%m)%m;\n        }\n        return ans%m;\n    }\n};\n```
['Sorting', 'Prefix Sum', 'C++']