Count of odd numbers in Array
Pattern: Traversal and in-place tricks
Count the odd values in one pass, with a remainder test that also works for negative numbers.
The problem
You are given an array of between 1 and 100,000 whole numbers, which may be negative. Return how many of them are odd.
For example, [3, 8, -5, 6] has 2 odd numbers, 3 and -5.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name countOdd and the limits are this guide's own.
Think first
- How do you test whether a number is odd?
- Work out -5 % 2 in your language. Is it 1?
- What single value do you carry along the array?
Hints
Brute force, and why it fails
There is no slower method worth comparing: every element has to be looked at once. The only real trap is the test for odd numbers, not the speed.
The key insight
One pass with a counter does it. The test x % 2 != 0 is correct for negative numbers in every language, while
x % 2 == 1 silently misses them in Java and C++.
Dry run
| count | 0 |
|---|
nums = [3, 8, -5, 6]. Start the count at 0.
The plan
count = 0
for x in nums:
if x mod 2 != 0: # odd, including negative odd numbers
count = count + 1
return count
Complexity
- Time
O(n)- Space
O(1)
One look at each element and a single counter.
Edge cases
- 0 is even.
- Negative odd numbers such as -3 must be counted.
- All even returns 0; all odd returns the length.
I've built my logic, show the code
Java
class Solution {
public int countOdd(int[] nums) {
int count = 0;
for (int x : nums) {
if (x % 2 != 0) { // also right for negative odd numbers
count++;
}
}
return count;
}
}C++
class Solution {
public:
int countOdd(vector<int>& nums) {
int count = 0;
for (int x : nums) {
if (x % 2 != 0) { // also right for negative odd numbers
count++;
}
}
return count;
}
};Python
class Solution:
def countOdd(self, nums):
count = 0
for x in nums:
if x % 2 != 0:
count += 1
return countCommon mistakes
- Testing
x % 2 == 1, which misses negative odd numbers in Java and C++. - Counting even numbers instead, by flipping the condition.