class Solution:
def arraySign(self, nums):
sign = 1
for num in nums:
if num == 0:
return 0
elif num < 0:
sign *= -1
return sign
class Solution {
public:
int arraySign(vector<int>& nums) {
int sign = 1;
for (int num : nums) {
if (num == 0) return 0;
else if (num < 0) sign *= -1;
}
return sign;
}
};
class Solution {
public int arraySign(int[] nums) {
int sign = 1;
for (int num : nums) {
if (num == 0) return 0;
else if (num < 0) sign *= -1;
}
return sign;
}
}
var arraySign = function(nums) {
let sign = 1;
for (let num of nums) {
if (num === 0) return 0;
else if (num < 0) sign *= -1;
}
return sign;
};
You are given an array of integers, nums
. Your task is to determine the sign of the product of all elements in the array, without actually calculating the product itself. The sign of a number is defined as:
1
if the product of all the elements is positive, -1
if negative, and 0
if the product is zero.
Constraints:
At first glance, it may seem like we need to multiply all the numbers in nums
and then check if the result is positive, negative, or zero. However, multiplying large numbers may cause overflow, and it's unnecessary to compute the actual product just to know its sign.
The key observation is that:
Let's break down the solution step-by-step:
sign = 1
. This will keep track of the sign of the product as we process each number.
0
, immediately return 0
since the product will be zero.sign
by -1
.sign
variable. It will be 1
if the product is positive, -1
if negative.
This method is efficient because:
Let's use the example nums = [-1, 2, -3, 4]
:
sign = 1
.
-1
(negative): flip sign to -1
.
2
(positive): sign stays -1
.
-3
(negative): flip sign to 1
.
4
(positive): sign stays 1
.
At the end, the sign is 1
, meaning the product is positive. If there had been a zero anywhere, we would have returned 0
immediately.
Brute-force approach:
O(n)
for n
elements, but with a risk of integer overflow.O(1)
since we only store the product.O(n)
— we make one pass through the array.O(1)
— only a single variable is used to track the sign.The optimized method is both safe and efficient, avoiding the risk of overflow.
By focusing on the sign rather than the actual product, we can efficiently determine the answer in a single pass without risk of overflow. The key insight is that only the number of negative numbers and the presence of zero matter. This approach is simple, elegant, and robust, making it ideal for both small and large input arrays.