Sponsored
Sponsored
This 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.
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.
1def arraySign(nums):
2 negative_count = 0
3 for num in nums:
4 if num == 0:
5 return 0
6 if num < 0:
7 negative_count += 1
8 return 1 if negative_count % 2 == 0 else -1
9
10print(arraySign([-1, -2, -3, -4, 3, 2, 1]))
The Python solution maintains a similar process to other languages with Pythonic constructs. The list is iterated, and the return depends on zero presence and negative count parity.
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.
Time Complexity: O(n)
Space Complexity: O(1)
1
In JavaScript, similar logic applied to determine product sign, efficient sign multiplication progresses and zero detection halts further computation, returning zero straightaway.