LeetCode 1822: Sign of the Product of an Array

ArrayMath

Problem Description

Explanation:

To solve this problem, we need to calculate the product of all elements in the given array nums. Then, we can determine the sign of the product based on the rules provided in the problem description.

  1. Initialize a variable product to store the product of all elements in the array.
  2. Iterate through each element in the array and update the product.
  3. Determine the sign of the product using the signFunc function.
  4. Return the sign of the product.

Time Complexity:

The time complexity of this solution is O(N), where N is the number of elements in the input array nums.

Space Complexity:

The space complexity of this solution is O(1) as we are using a constant amount of extra space.

Solutions

class Solution {
    public int arraySign(int[] nums) {
        int product = 1;
        for (int num : nums) {
            product *= num;
        }
        
        return signFunc(product);
    }
    
    private int signFunc(int x) {
        if (x > 0) {
            return 1;
        } else if (x < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}

Loading editor...