1822. Sign of the Product of an Array LeetCode Solution

In this guide, you will get 1822. Sign of the Product of an Array LeetCode Solution with the best time and space complexity. The solution to Sign of the Product of an Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sign of the Product of an Array solution in C++
  4. Sign of the Product of an Array solution in Java
  5. Sign of the Product of an Array solution in Python
  6. Additional Resources
1822. Sign of the Product of an Array LeetCode Solution image

Problem Statement of Sign of the Product of an Array

Implement 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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

1822. Sign of the Product of an Array LeetCode Solution in C++

class Solution {
 public:
  int arraySign(vector<int>& nums) {
    int sign = 1;

    for (const int num : nums) {
      if (num == 0)
        return 0;
      if (num < 0)
        sign = -sign;
    }

    return sign;
  }
};
/* code provided by PROGIEZ */

1822. Sign of the Product of an Array LeetCode Solution in Java

class Solution {
  public int arraySign(int[] nums) {
    int sign = 1;

    for (final int num : nums) {
      if (num == 0)
        return 0;
      if (num < 0)
        sign = -sign;
    }

    return sign;
  }
}
// code provided by PROGIEZ

1822. Sign of the Product of an Array LeetCode Solution in Python

class Solution:
  def arraySign(self, nums: list[int]) -> int:
    sign = 1

    for num in nums:
      if num == 0:
        return 0
      if num < 0:
        sign = -sign

    return sign
# code by PROGIEZ

Additional Resources

See also  3137. Minimum Number of Operations to Make Word K-Periodic LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.