|
| 1 | +# 🔥 Sum of Absolute Differences in a Sorted Array 🔥 || Simple Fast and Easy || with Explanation 😈 |
| 2 | + |
| 3 | +## Intuition |
| 4 | + |
| 5 | +The goal is to find the sum of absolute differences between each element and all other elements in the array. The code uses a prefix and suffix sum approach to efficiently calculate these absolute differences. |
| 6 | + |
| 7 | +### Approach |
| 8 | + |
| 9 | +1. **Suffix Sum Calculation (Initialization):** |
| 10 | + - Calculate the total sum of the array and store it in the variable `y`. This is done using a loop that iterates through each element of the array. |
| 11 | + |
| 12 | +2. **Absolute Difference Calculation:** |
| 13 | + - Iterate through the array again. |
| 14 | + - For each element, calculate the sum of absolute differences using the prefix sum (`x`) and the suffix sum (`y`). Update the element in the array with this calculated value. |
| 15 | + - Update the prefix sum (`x`) and suffix sum (`y`) accordingly for the next iteration. |
| 16 | + |
| 17 | +### Time Complexity |
| 18 | + |
| 19 | +- The time complexity of this algorithm is O(n), where n is the length of the input array. This is because the code iterates through the array twice, and each iteration takes O(n) time. |
| 20 | + |
| 21 | +### Space Complexity |
| 22 | + |
| 23 | +- The space complexity is O(1) since the algorithm uses a constant amount of additional space, regardless of the size of the input array. The input array is modified in place. |
| 24 | + |
| 25 | +This approach efficiently calculates the sum of absolute differences without the need for nested loops, resulting in a linear time complexity solution. |
| 26 | + |
| 27 | +## Code |
| 28 | + |
| 29 | +```go |
| 30 | +func getSumAbsoluteDifferences(nums []int) []int { |
| 31 | +// Initialize variables |
| 32 | +var x, y int = 0, 0 |
| 33 | +var len int = len(nums) |
| 34 | + |
| 35 | +// Calculate the total sum of the array (suffix sum) |
| 36 | +for i := 0; i < len; i++ { |
| 37 | +y += nums[i] |
| 38 | +} |
| 39 | + |
| 40 | +// Iterate through the array to calculate the absolute differences |
| 41 | +for i := 0; i < len; i++ { |
| 42 | +// Calculate the sum of absolute differences using prefix and suffix sums |
| 43 | +x += nums[i] |
| 44 | +tmp := (nums[i]*(i+1) - x) + (y - nums[i]*(len-i)) |
| 45 | + |
| 46 | +// Update the suffix sum for the next iteration |
| 47 | +y -= nums[i] |
| 48 | + |
| 49 | +// Update the array with the calculated absolute difference |
| 50 | +nums[i] = tmp |
| 51 | +} |
| 52 | + |
| 53 | +// Return the array with updated absolute differences |
| 54 | +return nums |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +## [GitHub](https://github.com/ayoubzulfiqar/leetcode) |
0 commit comments