Your solution is pretty much optimal with one change, as @Nemo indicates that the sum of integers from 1 to n is always (n+1) * n/2
It is also worth noting that your approach is multi-threaded (and can be used for very large N values), splits the array into parts, then receives the sum of each part of the array in the stream, and then adds those part of the sum. It depends on what the costs of stream processing are compared with adding numbers to the array.
If you are worried about overflows and your values ββare always int32 (since most .Length values ββinclude arrays), just save the sum as int64, the sum of all positive integer values (((long)int.MaxValue) +1L) * (int.MaxValue / 2) = 2305843007066210304 , which is still able to integrate into int64 using .MaxValue = 9223372036854775807 .
Another answer, as mentioned by others, is to XOR each element and keep running XOR, but then you need to develop a formula to get the expected final XOR in O(1) .
Most likely, the interviewer is looking to see if you understand the O(N) solution with O(1) memory (which is your answer), not array sorting, and much slower with very large N values.
To further improve your decision in the code, it would be to use a pointer to access the array, not the index value (what if your C # code would be a reasonable improvement).
source share