Sign of the Product of an Array
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Implement a function signFunc(x) that returns:
1ifxis positive.-1ifxis negative.0ifxis equal to0.
You are given an integer array nums. Let product be the product of all values in the array nums.
Return signFunc(product).
Examples
Example 1
Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
Example 2
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Example 3
Input: nums = [-1,1,-1,1,-1]
Output: -1
Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
Constraints
1 <= nums.length <= 1000-100 <= nums[i] <= 100
Solution
Method 1 – Count Negatives and Zeros
Intuition
The sign of the product is 0 if any element is 0, otherwise it is -1 if there are an odd number of negatives, else 1.
Approach
- Initialize a variable to count negatives.
- If any element is 0, return 0.
- If the count of negatives is odd, return -1; else return 1.
Code
C++
#include <vector>
using namespace std;
class Solution {
public:
int arraySign(vector<int>& nums) {
int neg = 0;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) ++neg;
}
return neg % 2 ? -1 : 1;
}
};
Java
class Solution {
public int arraySign(int[] nums) {
int neg = 0;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) ++neg;
}
return neg % 2 == 1 ? -1 : 1;
}
}
Python
class Solution:
def arraySign(self, nums):
neg = 0
for x in nums:
if x == 0:
return 0
if x < 0:
neg += 1
return -1 if neg % 2 else 1
Complexity
- ⏰ Time complexity:
O(n)— Single pass through the array. - 🧺 Space complexity:
O(1)— No extra space used.