The Leetcode problem asking to find out the sum of absolute differences of each of the array-element from other elements took some time to create the diffs on paper, try to figure out a pattern from those diffs and code the pattern. I was able to submit the solution and got it passed in one go. It is a medium strength problem. Here is the description of the problem:
You are given an integer array
numssorted in non-decreasing order.Build and return an integer array
resultwith the same length asnumssuch thatresult[i]is equal to the summation of absolute differences betweennums[i]and all the other elements in the array.In other words,
result[i]is equal tosum(|nums[i]-nums[j]|)where0 <= j < nums.lengthandj != i(0-indexed).
The constraints are:
2 <= nums.length <= 1051 <= nums[i] <= nums[i + 1] <= 104
Taking an int array 1, 2, 3, ..., 10 and writing all the diffs for each of the elements in the array, we can see the following, for example:
| 6-3 | = | 3-6 | = | 1-10 | - | 1-3 | - | 6-10 |
Do this for all the numbers for 6th element (i.e. | 6-1 |, | 6-2 |, etc.) and add them. If we do it for all the indexes in the array, we observe the following pattern:
(N-1) * | first - last | - (idx - 1)*| (No. at idx) - last | - (Sum of | first - Next | where 2nd element <= Next <= No. at idx) - (idx - 1)*| 1 - No. at idx | - (Sum of | No. at i - last| where idx+1 <= i <= last idx)
where,
N = total number of elements in the array
idx = index of current element
Here is the code and outputs for some sample intputs.
No comments:
Post a Comment