Back to solutions

Sign of An Array

EasyArrays

Return the sign of the product of all elements.

Constraints
  • 1 <= n <= 1000
  • -100 <= nums[i] <= 100

Track sign only

Time O(n)Space O(1)

You never need the actual product. Start with sign = 1. Any zero forces the answer to 0 immediately. Each negative number flips the sign. The final sign is the answer.

Key terms
sign:
Whether a number is positive (+1), negative (-1), or zero (0).
overflow:
When a real product would exceed the integer range; avoided by tracking only the 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;
}
Step by step
  1. Initialise sign = 1.
  2. For each value: if it is 0, return 0 right away.
  3. If it is negative, flip sign (sign = -sign).
  4. After the loop, return sign.