class Solution {
public:
int arraySign(vector<int>& nums) {
int countNeg = 0;
for (int num: nums) {
if (num == 0) return 0;
if (num < 0) countNeg++;
}
return (countNeg % 2 == 0) ? 1 : -1;
}
};
Logic:
Initialize countNeg to 0, which will store the count of negative numbers.
Iterate through each number num in the input array nums.
If num is 0, return 0 immediately, since any number multiplied by 0 is 0.
If num is negative, increment countNeg.
After iterating through all numbers, check if countNeg is even (i.e., countNeg % 2 == 0).
If even, return 1, since an even number of negative numbers will result in a positive product.
If odd, return -1, since an odd number of negative numbers will result in a negative product.
Test Cases:
Example 1:
Input: nums = [-1, -2, -3, -4, 3, 2, 1] Output: 1 Explanation: There are 4 negative numbers, which is an even count. The product will be positive.
Example 2:
Input: nums = [1, 2, 3, 4, -1, -2] Output: -1 Explanation: There are 2 negative numbers, which is an even count. However, the product will be positive. But then comes -3 which makes the count odd hence -1
Example 3:
Input: nums = [0, 1, 2, 3] Output: 0 Explanation: The array contains 0, so the product will be 0.
Example 4:
Input: nums = [-1, 1, -1, 1] Output: 1 Explanation: There are 2 negative numbers, which is an even count. The product will be positive.
Time Complexity: O(n), where n is the length of the input array.
Space Complexity: O(1), since only a single variable is used.
class Solution {
public:
int signFunc(int x) {
return (x > 0) ? 1 : (x < 0) ? -1 : 0;
}
int arraySign(vector<int>& nums) {
int result = 1 ;
for(auto n: nums){
result *= signFunc(n) ;
}
return result ;
}
};
Logic:
signFunc Function:
This function takes an integer x as input.
It returns:
1 if x is positive.
-1 if x is negative.
0 if x is zero.
Ternary Operator Explanation:
The signFunc function uses a ternary operator, which is a concise way to express a simple if-else statement.