HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

What is the best solution to find whether the sum of an array is even or odd

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
sumthewhatarrayfindevensolutionwhetheroddbest

Problem

I was asked this question in an interview. I was not able to find a better solution than $O(n)$ which is just going over the array and finding the sum. Can it be done any better? I am not really interested in the actual sum, I just want to know whether it's even or odd.

Or how do I prove that it cannot be done better than $O(n)$?

Solution

By a simple "adversary argument", you have to check each element (in some way): Suppose you have missed some element $x$ and get an answer "The sum is even": the adversary can modify $x$ (if it's odd, make it even; if it's even, make it odd), which will change the correct result but not your computation.

The adversary argument tells that in theory you have to check each element. By the way, it does not mean you have to sum them up. You can simply count the numbers of even numbers and odd numbers (or go through the array by +1 for even and -1 for odd).

Context

StackExchange Computer Science Q#40019, answer score: 12

Revisions (0)

No revisions yet.