15. Count Positive, Negative, and Zero Values
Given an array of integers, count how many values are positive, negative, and zero.
How It Works & Algorithmic Design
Each value belongs to exactly one of three categories:
- If
value > 0, increment the positive counter. - If
value < 0, increment the negative counter. - Otherwise, increment the zero counter.
- Return all three counts.
Why This Approach Works Best
A single traversal classifies every element. The algorithm uses $O(n)$ time and $O(1)$ auxiliary space.
Example Walkthrough
Input:
[-3, 5, 0, 8, -2, 0]The array contains all three possible categories.
Counts:
Positive=2 | Negative=2 | Zero=2Each number increments exactly one counter.
Output:
{ positive: 2, negative: 2, zero: 2 }The three counters represent the classification.
Answer: Count number categories
function countTypes(arr) {
let positive = 0;
let negative = 0;
let zero = 0;
for (const value of arr) {
if (value > 0) positive++;
else if (value < 0) negative++;
else zero++;
}
return { positive, negative, zero };
}💡 Use three counters and classify each value using conditional comparisons.
Key Takeaways
- Use mutually exclusive conditions when every value belongs to exactly one category.
- Three counters are sufficient for this problem.
- The solution requires O(n) time and O(1) space.