Sign of the Product of an Array - Problem

Implement a function signFunc(x) that returns:

  • 1 if x is positive.
  • -1 if x is negative.
  • 0 if x is equal to 0.

You are given an integer array nums. Let product be the product of all values in the array nums.

Return signFunc(product).

Input & Output

Example 1 — Mixed Signs
$ Input: nums = [-1,2,-3,4]
Output: 1
💡 Note: Product = (-1) × 2 × (-3) × 4 = 24. Since 24 > 0, return 1.
Example 2 — Contains Zero
$ Input: nums = [1,5,0,2,-3]
Output: 0
💡 Note: Product = 1 × 5 × 0 × 2 × (-3) = 0. Since product equals 0, return 0.
Example 3 — Odd Negatives
$ Input: nums = [-1,-2,-3]
Output: -1
💡 Note: Product = (-1) × (-2) × (-3) = -6. Since -6 < 0, return -1.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Sign of Product: Smart Analysis vs Brute ForceInput Array-12-34Smart Analysis:• No zeros found ✓• Count negatives: 2 (even)• Even negatives → Positive resultBrute Force Approach:Calculate: (-1)×2×(-3)×4 = 24Risk: Integer overflow!Optimized Approach:Count: 2 negatives (even)Safe: No overflow risk!Output: 1 (Positive)
Understanding the Visualization
1
Input
Array of integers with mixed signs
2
Analysis
Count negatives and check for zeros
3
Output
Return 1, -1, or 0 based on product sign
Key Takeaway
🎯 Key Insight: We only need the sign, not the actual product - count negatives to avoid overflow
Asked in
Amazon 15 Facebook 10
25.0K Views
Medium Frequency
~10 min Avg. Time
850 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