Sign of An Array

Tell whether the product of an array's numbers is positive, negative or zero, without multiplying them.

Take an array of integers nums and multiply all its numbers together, and call the result the product. Return 1 if the product is positive, -1 if it is negative, and 0 if it is zero. The array holds between 1 and 1000 numbers, each between -100 and 100.

Example 1
Input: nums = [-1, -2, -3, -4, 3, 2, 1]
Output: 1
Explanation: the product is 144, which is positive.
Example 2
Input: nums = [1, 5, 0, 2, -3]
Output: 0
Explanation: the product is 0.
Example 3
Input: nums = [-1, 1, -1, 1, -1]
Output: -1
Explanation: the product is -1, which is negative.
Solution

The Idea

You learned the sign rules for multiplication at school: a minus times a minus gives a plus, and a minus times a plus gives a minus. Anything times zero is zero. This problem asks us to apply those rules to a whole array at once.

The obvious way is to multiply everything and look at the result. For Example 1 that works: -1 times -2 times -3 times -4 times 3 times 2 times 1 is 144, so the answer is 1. But the array can hold 1000 numbers of size 100, and their product can be 100 multiplied by itself 1000 times. That is a 1 followed by 2000 zeros, far too big for an int or even a long. So can we find the sign without ever computing the product?

We can, because the size of each number never changes the sign. Only two things do: whether a number is negative, and whether it is zero. Look at the picture below.

Reading Example 1 left to right, the sign so far starts at +1 and flips at each of the four negative numbers, ending at +1. In Example 2 the walk stops at the 0, and the answer is 0.

In the top row, read Example 1 from left to right and keep only the sign so far. The first number, -1, makes it -1. Then -2 flips it back to +1, -3 flips it to -1, and -4 flips it to +1 again. The positive numbers 3, 2 and 1 leave it alone, so the answer is 1.

In the bottom row, Example 2 starts the same way, with 1 and 5 keeping the sign at +1. Then comes 0. Whatever follows, the product is now 0, so there is no need to look at 2 or -3.

So the answer depends only on whether the array has a zero and, if not, on how many negative numbers it has. An even count gives a positive product, and an odd count gives a negative one.

Solution Approach

Turning that idea into code means settling two things: how to keep track of the sign, and what to do when a zero turns up.

Keeping track of the sign

How do we remember the sign without the product? Keep a single variable sign that starts at 1, the sign of a product that has no negative numbers in it yet. Each negative number turns 1 into -1 or -1 into 1, which is just sign = -sign. Positive numbers change nothing, so the code skips them.

Counting the negative numbers and checking at the end whether the count is even would work just as well. Flipping sign as we go does the same thing and leaves the answer ready to return.

Stopping at a zero

What should happen at a zero? The product is 0 from then on, whatever numbers come later, so the method can return 0 at once. That also saves reading the rest of the array.

Java Solution

The method arraySign works in these steps:

  1. First, set sign to 1.
  2. Go through the array with one loop, taking each number as x.
  3. If x is 0, return 0 right away.
  4. If x is negative, flip sign with sign = -sign.
  5. When the loop ends without meeting a zero, return sign.

The main method runs the three examples, an array of a single negative number, and an array whose zero comes last. It then compares arraySign with naiveSign, which multiplies the numbers in an int, on six -100s and on forty 2s.

Java
import java.util.Arrays;

public class SignOfAnArray {

    public static int arraySign(int[] nums) {
        int sign = 1;
        for (int x : nums) {
            if (x == 0) {
                return 0;                     // one zero makes the product 0
            }
            if (x < 0) {
                sign = -sign;                 // each negative number flips the sign
            }
        }
        return sign;
    }

    // The tempting way: multiply everything, then look at the result.
    static int naiveSign(int[] nums) {
        int product = 1;
        for (int x : nums) {
            product *= x;
        }
        return Integer.signum(product);
    }

    public static void main(String[] args) {
        System.out.println(arraySign(new int[] {-1, -2, -3, -4, 3, 2, 1}));
        System.out.println(arraySign(new int[] {1, 5, 0, 2, -3}));
        System.out.println(arraySign(new int[] {-1, 1, -1, 1, -1}));
        System.out.println(arraySign(new int[] {-7}));
        System.out.println(arraySign(new int[] {-5, -5, -5, 0}));

        int[] sixNegatives = new int[6];
        Arrays.fill(sixNegatives, -100);
        int[] fortyTwos = new int[40];
        Arrays.fill(fortyTwos, 2);
        System.out.println("six -100s: arraySign " + arraySign(sixNegatives)
                + ", naive " + naiveSign(sixNegatives));
        System.out.println("forty 2s:  arraySign " + arraySign(fortyTwos)
                + ", naive " + naiveSign(fortyTwos));
    }
}

Running it prints:

Output
1
0
-1
-1
0
six -100s: arraySign 1, naive -1
forty 2s:  arraySign 1, naive 0

The first three lines, 1, 0 and -1, match the three examples. Next, [-7] prints -1: one negative number is an odd count. The 0 after it comes from [-5, -5, -5, 0]. Three negatives would give -1, but the zero at the end still wins.

The last two lines show why the method never multiplies. Six -100s multiply to 1,000,000,000,000, which is positive, but an int holds values only up to about 2.1 billion. Past that it wraps around to negative values, which is called overflow. Here the int product comes out as -727,379,968, so naiveSign says -1. Forty 2s overflow all the way to exactly 0, so naiveSign says 0. arraySign returns 1 for both.

The original implementation, SignOfArray.java, is on GitHub.

Complexity

The work is one pass over the array, with two checks per number.

  • Time: O(n), because the loop looks at each of the n numbers in the array at most once, and stops early at the first zero.
  • Space: O(1). Only sign and the current number are kept, however long the array is.

Keeping track of what negative numbers do to a product also matters in Maximum Product Subarray, where one more negative number can turn the smallest product into the largest.