Program to find sign of the product of an array using Python

Finding the sign of a product without actually computing the multiplication is an efficient approach that avoids overflow issues. We can determine the result by counting zeros and negative numbers in the array.

Algorithm

The key insight is that we don't need to calculate the actual product. Instead ?

  • If any element is zero, the product is zero

  • If there's an even number of negative elements, the product is positive

  • If there's an odd number of negative elements, the product is negative

Example

def find_product_sign(nums):
    zeroes = 0
    negatives = 0
    
    for num in nums:
        if num == 0:
            zeroes += 1
        elif num < 0:
            negatives += 1
    
    if zeroes > 0:
        return "Zero"
    elif negatives % 2 == 0:
        return "Positive"
    else:
        return "Negative"

# Test with the given example
nums = [-2, 3, 6, -9, 2, -4]
result = find_product_sign(nums)
print(f"Array: {nums}")
print(f"Product sign: {result}")
Array: [-2, 3, 6, -9, 2, -4]
Product sign: Negative

How It Works

For the array [-2, 3, 6, -9, 2, -4] ?

  • Negative numbers: -2, -9, -4 (count = 3)

  • Zero numbers: none (count = 0)

  • Since there are no zeros and 3 (odd) negative numbers, the result is "Negative"

Testing Different Cases

def find_product_sign(nums):
    zeroes = 0
    negatives = 0
    
    for num in nums:
        if num == 0:
            zeroes += 1
        elif num < 0:
            negatives += 1
    
    if zeroes > 0:
        return "Zero"
    elif negatives % 2 == 0:
        return "Positive"
    else:
        return "Negative"

# Test different cases
test_cases = [
    [1, 2, 3, 4],        # All positive
    [-1, -2, 3, 4],      # Even negatives
    [-1, -2, -3, 4],     # Odd negatives
    [1, 0, 3, 4],        # Contains zero
]

for nums in test_cases:
    result = find_product_sign(nums)
    print(f"{nums} ? {result}")
[1, 2, 3, 4] ? Positive
[-1, -2, 3, 4] ? Positive
[-1, -2, -3, 4] ? Negative
[1, 0, 3, 4] ? Zero

Time and Space Complexity

  • Time Complexity: O(n) where n is the length of the array

  • Space Complexity: O(1) as we only use constant extra space

Conclusion

This approach efficiently determines the product sign by counting zeros and negative numbers, avoiding potential overflow issues from actual multiplication. The algorithm runs in linear time with constant space complexity.

Updated on: 2026-03-25T20:53:27+05:30

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements