Sign of the Product of an Array
Problem
Return 1 if the product of nums is positive, −1 if negative, 0 if any element is 0.
nums = [-1,-2,-3,-4,3,2,1]1def array_sign(nums):
sign = 1
for x in nums:
if x == 0: return 0
if x < 0: sign = -sign
return sign
function arraySign(nums) {
let sign = 1;
for (const x of nums) {
if (x === 0) return 0;
if (x < 0) sign = -sign;
}
return sign;
}
class Solution {
public int arraySign(int[] nums) {
int sign = 1;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) sign = -sign;
}
return sign;
}
}
int arraySign(vector<int>& nums) {
int sign = 1;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) sign = -sign;
}
return sign;
}
Explanation
We never actually multiply the numbers — that could overflow and we don't care about the value, only the sign. So we just track whether the running sign is positive or negative.
Start with sign = 1. Walk through each element: if it's 0, the whole product is 0, so we can short-circuit and return 0 immediately. If it's negative, we flip the sign with sign = -sign. Positive numbers don't change anything.
At the end, sign is +1 if there were an even number of negatives and -1 if odd — exactly the sign of the real product.
Example: nums = [-1, -2, -3, -4, 3, 2, 1] has four negatives. Each one flips the sign, and four flips land back on +1, so the answer is 1.
It works because a product's sign depends only on how many negative factors there are (and whether any factor is zero), not on the magnitudes.