Sign of the Product of an Array LeetCode Solution

Difficulty Level Easy
Frequently asked in MicrosoftViews 3231

Problem Statement

Sign of the Product of an Array LeetCode Solution – 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).

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

Sign of the Product of an Array LeetCode Solution

Explanation

  • Simple intuition is rather than multiplying we check for negatives and zeroes because this is what will make an effect on the answer.
  • So, we will check if anytime we encounter an 0 in the array, then we return 0. As any number multiplied by 0 gives 0.
  • Secondly, if nums[i]<0 means if it is negative then increment the count of n i.e n++.
  • After coming out of the loop, check if n is odd or even? This is because we know if 2 negative numbers are multiplied, they will always give a +ve number. So if n is even, then return +1. And if it is odd, then return -1.

If we encounter a 0, we can return immediately. Otherwise, keep track of the negatives. If the count of negatives is odd, the product is negative. If the count of negatives is even, the product is positive.

Code

C++ Code for Sign of the Product of an Array

class Solution {
public:
    int arraySign(vector<int>& nums) {
        int i , count_neg = 0;
        for(i=0 ; i<nums.size() ; i++)
        {
            if(nums[i] == 0)
                return 0;
            else if(nums[i] < 0)
                count_neg++;
        }
        if(count_neg %2 == 0)
            return 1;
        else
            return -1;
    }
};

Java Code for Sign of the Product of an Array

class Solution {
    public int arraySign(int[] nums) {
        int sign = 1; 
        for (int n : nums) {
            if (n == 0) {
                return 0; 
            } 
      if (n < 0) {
                sign = -sign; 
            }
        }
        return sign; 
    }
}

Python Code for Sign of the Product of an Array

class Solution:
    def arraySign(self, nums: List[int]) -> int:
        result = 1
        for n in nums:
            if not n:
                return n
            if n < 0:
                result = -result
        return result

Complexity Analysis for Sign of the Product of an Array LeetCode Solution

Time Complexity

O (n) since we make a single pass to the array.

Space Complexity

O(1) since we take only a single variable into consideration.

Reference: https://en.wikipedia.org/wiki/Array_data_structure

 

Translate »