Count Positive and Negative Numbers in an Array
Solve this ProblemEasy5 min
Topics
BasicsArrays
Companies
TCSInfosysWipro
Given an array
nums, return [positives, negatives, zeros]: how many elements are greater than 0, less than 0, and exactly 0.
Classifying a single number by its sign is a conditionals exercise; doing it for a whole array adds a loop and three counters. Zero is the case that is easiest to forget — it is neither positive nor negativeSign of ZeroZero is the boundary between positive and negative numbers and belongs to neither group. — and the second solution shows it does not even need its own branch.
Test Case 1:
Input:nums = [3, -1, 0, 8, -6]
Output:[2, 2, 1]
Explanation:Two positives (3, 8), two negatives (−1, −6) and one zero.
Test Case 2:
Input:nums = [0, 0]
Output:[0, 0, 2]
Explanation:Zero is neither positive nor negative.
Constraints
- ◆
1 ≤ nums.length ≤ 1000 - ◆
-1000000 ≤ nums[i] ≤ 1000000
Try the Dry Run
Approach & Solutions
If-Else ChainGood
Keep three counters. For each value, check greater than 0 first, then less than 0; anything left must be exactly 0. Return [positives, negatives, zeros].
Time
O(n)Space
O(1)Java
class Solution {
public int[] countSigns(int[] nums) {
int positives = 0, negatives = 0, zeros = 0;
for (int value : nums) {
if (value > 0) {
positives++;
} else if (value < 0) {
negatives++;
} else {
zeros++;
}
}
return new int[] {positives, negatives, zeros};
}
}Count Two, Derive the ThirdOptimal
Positive, negative and zero split the array into three groups that always add up to its length. Count positives and negatives in the loop, then compute zeros = length − positives − negatives afterwards.
Time
O(n)Space
O(1)Java
class Solution {
public int[] countSigns(int[] nums) {
int positives = 0, negatives = 0;
for (int value : nums) {
if (value > 0) {
positives++;
} else if (value < 0) {
negatives++;
}
}
int zeros = nums.length - positives - negatives;
return new int[] {positives, negatives, zeros};
}
}