This is what i came thru a problem in some coding test.
problem statement was like that we have to add all the elements of an array except the element at the index. subtraction operator cannot be used here and complexity should be O(n).
like
arr={3,7,8,4,9}
then result array will be... sum={28,24,23,27,22}
i have think a lot over it. but still missing something. some hint or pseudo code will be appreciable.
Concluded: if there is not any other reasonable answer to this then achieving subtraction by any mean could be possible solution. i have concluded it with using -1*arr[i] or complexity will be O(n2).
Edit: Above conclusion is not correct.
A simple O(n) approach that uses only addition (and no "cheats" like -1*elem
or ~elem + 1
to simulate subtraction) is to do two passes:
Create the result array sum
:
int[] sum = new int[n];
In a "forward" pass from index 0 to index nā1, set each element of sum
to the sum of all "previous" elements in arr
:
int sumOfAllPrevious = 0;
for (int i = 0; i < n; ++i) {
sum[i] = sumOfAllPrevious;
sumOfAllPrevious += arr[i];
}
In a "reverse" pass from index nā1 to index 0, augment each element of sum
with the sum of all "later" elements in arr
:
int sumOfAllLater = 0;
for (int i = n - 1; i >= 0; --i) {
sum[i] += sumOfAllLater;
sumOfAllLater += arr[i];
}