11. Count Odd Numbers in an Array
Given an array of integers, count how many values are odd.
How It Works & Algorithmic Design
An integer is odd when dividing it by 2 leaves a remainder of 1 or -1. We can detect this using the modulo operator:
- Initialize
count = 0. - Traverse every element in the array.
- Check whether
value % 2 !== 0. - If the condition is true, increment
count. - Return the final count.
Why This Approach Works Best
Every element must be inspected once, giving $O(n)$ time complexity. Only one counter is required, so the auxiliary space is $O(1)$.
Example Walkthrough
Input:
[2, 5, 7, 8, 11, 14]The array contains both even and odd numbers.
Evaluation:
2 -> Even | 5 -> Odd | 7 -> Odd | 8 -> Even | 11 -> Odd | 14 -> EvenOnly odd values increase the counter.
Output:
3The odd numbers are 5, 7, and 11.
Answer: Count odd values
function countOdd(arr) {
let count = 0;
for (const value of arr) {
if (value % 2 !== 0) count++;
}
return count;
}💡 Traverse the array and use modulo 2 to determine whether each number is odd.
Key Takeaways
- The modulo operator helps determine whether an integer is odd or even.
- Every element must be checked, so the time complexity is O(n).
- Only a counter is required, giving O(1) auxiliary space.