NeetCode #131LC-1822EasyArrays & Hashing
← Back to All Problems

#131 · #1822 · Sign of the Product of an Array(数组元素积的符号)

📌 Problem Statement & Constraints

The sign of an array is 1 if the product of all elements is positive, -1 if negative, and 0 if the product is zero. Given nums, return its sign. Constraints: 1 <= nums.length <= 1000, -100 <= nums[i] <= 100.

💡 Core Algorithmic Approaches

  1. Never compute the product -- it can overflow and it is unnecessary.
  2. A zero anywhere forces the answer to 0.
  3. Otherwise only the parity of the number of negative elements matters.
  4. Track the sign by flipping a flag on each negative element.

💻 Benchmark Python3 Implementation

class Solution:
    def arraySign(self, nums: List[int]) -> int:
        sign = 1
        for x in nums:
            if x == 0:
                return 0                   # zero dominates
            if x < 0:
                sign = -sign               # each negative flips the sign
        return sign

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) with an early exit on the first zero.
💾 Space Complexity
O(1): a single sign flag.

⚠️ Interview Pitfalls & Follow-ups

  • Computing the actual product: it overflows in fixed-width languages and is pointless here.
  • Counting negatives and then taking (-1) count**: correct but the incremental flip is simpler.
  • Forgetting the zero case: [1, 0, -1] must return 0, not -1.
  • Using math.prod: same overflow concern and still O(n).