algoadvance

Leetcode 1822. Sign of the Product of an Array

Problem Statement

You are given an integer array nums. Let product be the product of all values in the array nums.

Return 1 if product is positive, -1 if product is negative, and 0 if product is zero.

Clarifying Questions

  1. What are the constraints on the size of the array?
    • The array length can be up to 1000.
  2. What are the constraints on the values within the array?
    • Each element in the array is an integer between -100 and 100.
  3. Is it necessary to calculate the actual product of the elements?
    • No, we only need to determine the sign of the product.

Strategy

To determine the sign of the product of an array without actually computing the potentially large product, we can use the following approach:

  1. Check for Zeros: If any element is zero, the product is zero, and we return 0.
  2. Count Negative Numbers: If the number of negative values is odd, the product will be negative, otherwise, it will be positive.

Pseudocode

  1. Initialize a counter for negative numbers.
  2. Iterate through the array:
    • If an element is zero, return 0.
    • If an element is negative, increment the negative counter.
  3. After the loop, if the count of negative numbers is odd, return -1; if even, return 1.

Code

#include <vector>

class Solution {
public:
    int arraySign(std::vector<int>& nums) {
        int negativeCount = 0;

        for (int num : nums) {
            if (num == 0) {
                return 0;
            } else if (num < 0) {
                negativeCount++;
            }
        }

        if (negativeCount % 2 == 0) {
            return 1;
        } else {
            return -1;
        }
    }
};

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI