✅ Beats 100% - Explained with [ Video ] - Two Pointers - Visualized Too
\n\n\n # YouTube Video Explanation:\n\n<a href="https://youtu.be/QncjaI-st-w">https://youtu.be/QncjaI-st-w</a>\n\n**\uD83D\uDD25 Please like, share, and subscri
![Screenshot 2023-11-25 073517.png](https://assets.leetcode.com/users/images/4aee67b1-1589-4f5a-98c2-31db86a1558e_1700877952.489825.png)\n\n\n<!-- # YouTube Video Explanation:\n\n[https://youtu.be/QncjaI-st-w](https://youtu.be/QncjaI-st-w)\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 500 Subscribers*\n*Current Subscribers: 405*\n\n--- -->\n# Example Explanation\nStep-by-Step Explanation:\n\n 1. **Calculate Total Sum:**\n    - Calculate the total sum of the array.\n\n 2. **Initialize Pointers:**\n    - Initialize two pointers, `left` and `right`, at the start and end of the array.\n\n 3. **Iterate Through the Array:**\n    - For each element `nums[i]`:\n       a. Calculate the absolute difference sum using `left` and `right`.\n       b. Update `left` by adding the current element.\n       c. Update `right` by subtracting the current element.\n       d. Store the result in the output array `r[i]`.\n\nIllustration:\n\n| Iteration | Element (nums[i]) | Absolute Difference Sum Formula         | Result (r[i]) |\n|-----------|---------------------|------------------------------------------|---------------|\n| 1         | nums[0] = 2         | 2 * 0 - 0 + (sum - 2) - 2 * (5 - 1)      | Result[0]     |\n| 2         | nums[1] = 3         | 3 * 1 - 2 + (sum - 3) - 3 * (5 - 2)      | Result[1]     |\n| 3         | nums[2] = 5         | 5 * 2 - (2 + 3) + sum - 5 - 5 * (5 - 3) | Result[2]     |\n\n... and so on.\n\nFinal Output: The array `r` containing the result for each element.\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe objective is to calculate the sum of absolute differences between each element and all other elements in the array. The key observation here is that we can efficiently compute the result for each element by considering the differences between consecutive elements.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First, calculate the total sum of the array. This sum will be used to compute the right part of the absolute differences.\n2. Initialize two pointers, `left` and `right`, pointing to the start and end of the array.\n3. Iterate through the array, and for each element `nums[i]`, calculate the absolute difference sum by considering the left and right parts.\n   - `left` represents the sum of elements to the left of `nums[i]`.\n   - `right` represents the sum of elements to the right of `nums[i]`.\n   - The absolute difference sum for `nums[i]` is calculated as `n * i - left + right - n * (nums.length - i - 1)`.\n4. Update the `left` pointer by adding the current element to it.\n5. Update the `right` pointer by subtracting the current element from it.\n6. Store the result in the output array `r`.\n\n# Complexity\n- Time Complexity: O(N) - We iterate through the array once.\n- Space Complexity: O(N) - The output array `r` is used to store the results.\n\n# Code\n## Java\n```\nclass Solution {\n    public int[] getSumAbsoluteDifferences(int[] nums) {\n        int sum = 0;\n        for (int n : nums) {\n            sum += n;\n        }\n        int left = 0;\n        int right = sum;\n\n        int[] r = new int[nums.length];\n\n        for (int i = 0; i < nums.length; i++) {\n            int n = nums[i];\n            right -= n;\n\n            r[i] = n * i - left + right - n * (nums.length - i - 1);\n\n            left += n;\n        }\n\n        return r;\n    }\n}\n```\n## C++\n```\nclass Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        int sum = 0;\n        for (int n : nums) {\n            sum += n;\n        }\n        int left = 0;\n        int right = sum;\n\n        std::vector<int> result(nums.size(), 0);\n\n        for (int i = 0; i < nums.size(); i++) {\n            int n = nums[i];\n            right -= n;\n\n            result[i] = n * i - left + right - n * (nums.size() - i - 1);\n\n            left += n;\n        }\n\n        return result;\n    }\n};\n```\n## Python\n```\nclass Solution(object):\n    def getSumAbsoluteDifferences(self, nums):\n        total_sum = sum(nums)\n        left, right = 0, total_sum\n        result = []\n\n        for i, n in enumerate(nums):\n            right -= n\n            result.append(n * i - left + right - n * (len(nums) - i - 1))\n            left += n\n\n        return result\n               \n```\n## JavaScript\n```\nvar getSumAbsoluteDifferences = function(nums) {\n    let totalSum = nums.reduce((sum, n) => sum + n, 0);\n    let left = 0, right = totalSum;\n    let result = [];\n\n    for (let i = 0; i < nums.length; i++) {\n        right -= nums[i];\n        result.push(nums[i] * i - left + right - nums[i] * (nums.length - i - 1));\n        left += nums[i];\n    }\n\n    return result;\n};\n```\n![upvote1.jpeg](https://assets.leetcode.com/users/images/5af6e91c-b3a7-45b7-9dd6-94697161d56f_1700878113.4450402.jpeg)\n
['Array', 'Math', 'Two Pointers', 'Prefix Sum', 'Python', 'C++', 'Java', 'JavaScript']