javaalgorithm

Adding all elements of an array except the element at index with O(n) complexity


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.


Solution

  • 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: