#1822

Sign of the Product of an Array

Easy
ArrayMathArrayMathematics
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of calculating the product directly, we can determine the sign of the product by counting the number of negative numbers and checking for zeros. This avoids overflow and unnecessary calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a counter for negative numbers and a flag for zero.
  2. 2Step 2: Iterate through the array and update the counter for negatives and set the zero flag if a zero is found.
  3. 3Step 3: If zero is found, return 0. Otherwise, return 1 if the count of negatives is even, otherwise return -1.
solution.py8 lines
1def arraySign(nums):
2    negative_count = 0
3    for num in nums:
4        if num == 0:
5            return 0
6        if num < 0:
7            negative_count += 1
8    return 1 if negative_count % 2 == 0 else -1

Complexity note: The time complexity remains O(n) as we still iterate through the array once. The space complexity is O(1) since we only use a few extra variables.

  • 1The presence of zero in the array immediately determines the product's sign.
  • 2The sign of the product can be determined by counting negative numbers.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.