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).
Example 1:
Input: nums = [-1,-2,-3,-4,3,2,1] Output: 1 Explanation: The product of all values in the array is 144, and signFunc(144) = 1
Example 2:
Input: nums = [1,5,0,2,-3] Output: 0 Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Example 3:
Input: nums = [-1,1,-1,1,-1] Output: -1 Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
Constraints:
1 <= nums.length <= 1000-100 <= nums[i] <= 100This approach involves scanning through the array once to check for any zeros and counting the number of negative numbers. If there's a zero, the product is zero. Otherwise, if the number of negative numbers is odd, the product is negative; if even, the product is positive.
The C solution uses a loop to iterate over the array. If a zero is found immediately return zero, otherwise count the number of negative integers. If the count is even, return 1. If odd, return -1.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the number of elements in the array. We only need to pass over the array once.
Space Complexity: O(1), as no additional space beyond the given variables is used.
This approach uses a multiplicative identity set as variable 'sign', initialized to 1. Then iterates through each element of the array, multiplying 'sign' with -1 for each negative number and returning zero if a zero is found.
This C code sets a 'sign' variable to 1 and iterates over the input. It flips the sign by multiplying it by -1 for each negative number found, returning 0 immediately upon encountering a zero.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Zero and Negative Count Check | Time Complexity: O(n), where n is the number of elements in the array. We only need to pass over the array once. |
| Multiplicative Identity and Sign Evaluation | Time Complexity: O(n) |
Product of Array Except Self - Leetcode 238 - Python • NeetCode • 747,485 views views
Watch 9 more video solutions →Practice Sign of the Product of an Array with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor