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 the Product of an Array INPUT nums = [-1, 2, -3, 4] -1 index 0 2 index 1 -3 index 2 4 index 3 Sign Analysis: Negative: 2 Positive: 2 Zero: 0 signFunc(x): x > 0 --> 1 x < 0 --> -1 x = 0 --> 0 ALGORITHM STEPS 1 Initialize Counters negCount = 0, zeroCount = 0 2 Scan Array Count negatives and zeros -1: neg++ --> negCount=1 2: positive (skip) -3: neg++ --> negCount=2 4: positive (skip) 3 Check for Zero If zeroCount > 0, return 0 4 Determine Sign negCount even --> 1 negCount odd --> -1 FINAL RESULT Final Counts: negCount = 2 zeroCount = 0 2 is EVEN Decision Logic: zeroCount = 0? YES negCount even? YES Output: 1 Product sign is POSITIVE Key Insight: We don't need to calculate the actual product (which could overflow). Instead, count zeros and negatives: - If any zero exists, product = 0. Otherwise, even negatives = positive product, odd negatives = negative. Time: O(n) | Space: O(1) TutorialsPoint - Sign of the Product of an Array | Count Negatives and Zeros Approach
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