Sign of the Product of an Array - Problem

Given an integer array nums, you need to determine the sign of the product of all elements in the array without actually calculating the product itself.

The challenge is to implement a function that returns:

  • 1 if the product is positive
  • -1 if the product is negative
  • 0 if the product is zero

Key insight: You don't need to calculate the actual product (which could overflow), just determine its sign! Think about what makes a product positive, negative, or zero.

Example: For [1, 5, 0, 2, -3], since there's a zero, the product is 0, so return 0.

Input & Output

example_1.py โ€” Basic positive result
$ Input: nums = [-1,1,-1,1,1]
โ€บ Output: 1
๐Ÿ’ก Note: The product is (-1) * 1 * (-1) * 1 * 1 = 1, which is positive, so return 1. Alternatively, count negatives: 2 negatives (even) = positive result.
example_2.py โ€” Negative result
$ Input: nums = [-1,1,-1,1,-1]
โ€บ Output: -1
๐Ÿ’ก Note: The product is (-1) * 1 * (-1) * 1 * (-1) = -1, which is negative, so return -1. Count negatives: 3 negatives (odd) = negative result.
example_3.py โ€” Zero in array
$ Input: nums = [-1,1,0,1,-1]
โ€บ Output: 0
๐Ÿ’ก Note: Since there's a 0 in the array, the product is 0, so return 0. Any zero makes the entire product zero.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • -100 โ‰ค nums[i] โ‰ค 100
  • No need to calculate actual product - avoid overflow issues

Visualization

Tap to expand
Sign Determination: The Light Switch Analogy+Start: Positive-2 (flip)-Now: Negative-3 (flip)+Back to: Positive5 (no flip)+Still: PositiveRules:โ€ข Any zero โ†’ Result is 0โ€ข Even negatives โ†’ Positiveโ€ข Odd negatives โ†’ NegativeExample: [-2, -3, 5]2 negatives (even) = Positive
Understanding the Visualization
1
Check for Zero
If any element is 0, the entire product becomes 0
2
Count Negatives
Each negative number flips the sign of the product
3
Apply Sign Rule
Even count of negatives = positive, odd count = negative
Key Takeaway
๐ŸŽฏ Key Insight: The sign of a product depends only on the parity (even/odd) of negative numbers, not their actual values!
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
23.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen