Sign of the Product of an Array — Problem & Solution
Sign of the Product of an Array solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Sign of the Product of an Array is an easy coding problem on arrays and math, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Arrays, Math
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Let product be the product of every value in nums.
Return 1 if product is positive, -1 if it is negative, and 0 if it is zero.
Example 1
Input: nums = [-1,-2,-3,-4,3,2,1]
Output: 1
Explanation: Four negatives multiply to a positive.
Example 2
Input: nums = [1,5,0,2,-3]
Output: 0
Explanation: A single zero zeroes the whole product.
Example 3
Input: nums = [-1,1,-1,1,-1]
Output: -1
Constraints
1 <= nums.length <= 1000-100 <= nums[i] <= 100
Hints for Sign of the Product of an Array
Hint 1
Do not compute the product — it overflows long before you need it.
Hint 2
Only two facts matter: whether any element is zero, and how many are negative.
Hint 3
Flip a running sign on every negative and bail out immediately on a zero.
How to solve Sign of the Product of an Array
The sign of a product depends only on the parity of the negative-factor count, and any zero factor short-circuits everything.
Approach
- Start with
sign = 1. - Scan the array. On a
0, return0immediately. - On a negative value, flip
sign. - Return
signat the end.
Why it works
Multiplying by a negative number flips the sign exactly once, so after k negatives the sign is (-1)^k — which the running flip computes without ever forming the product.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Actually multiplying overflows every fixed-width integer type at these limits.
- Counting negatives but forgetting the zero check returns ±1 for an array containing 0.
Reference solution
Python
from typing import List
def arraySign(nums: List[int]) -> int:
sign = 1
for x in nums:
if x == 0:
return 0
if x < 0:
sign = -sign
return signJava
public static int arraySign(int[] nums) {
int sign = 1;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) sign = -sign;
}
return sign;
}C++
int arraySign(vector<int>& nums) {
int sign = 1;
for (int x : nums) {
if (x == 0) return 0;
if (x < 0) sign = -sign;
}
return sign;
}JavaScript
var arraySign = function(nums) {
let sign = 1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] === 0) return 0;
if (nums[i] < 0) sign = -sign;
}
return sign;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays