Leetcode - Sign of the Product of an Array

February 8th, 2024
Description

There is a function signFunc(x) that returns:

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0. You are given an integer array nums. Let product be the product of all values in the array nums. Return signFunc(product).

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

When I was thinking of a way to approach this problem, I immediately realized that I did not actually have to do any calculations to figure out if the number was negative, positive, or a zero.

  1. If there is a zero anywhere in the nums array, the answer is automatically 0. Once I encounter a 0, there's no further need to proceed.
  2. If the number is negative, it will flip the sign. I will need to keep track if the current product is a positive. Every time I come across a negative number, this will change the sign from positive to negative or vice-versa.

With that, I'll use a boolean to keep track of whether or not the current product is positive (pos). I'll then iterate through nums and apply changes to pos or return 0 when appropriate. If we get through nums with no zeroes, we will then return 1 if the product is positive, and -1 if negative.

function arraySign(nums: number[]): number {
    let pos = true;

    for (let i = 0; i < nums.length; i++) {
        if (nums[i]) {
            if (nums[i] < 0) {
                if (pos) {
                    pos = false;
                } else {
                    pos = true;
                }
            }
        } else {
            return 0;
        }
    }

    if (pos) {
        return 1;
    } else {
        return -1;
    }
};

This code has a runtime of 56 ms and a memory usage of 51.23 MB.