Skip to content

1822. Sign of the Product of an Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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