Similar Problems
Similar Problems not available
Sign Of The Product Of An Array - Leetcode Solution
Companies:
LeetCode: Sign Of The Product Of An Array Leetcode Solution
Difficulty: Easy
Problem Statement:
Given an array of integers nums, determine the sign of the product of all the elements in the array.
Return 1 if the product is positive, -1 if the product is negative, and 0 if the array has a zero element.
Solution:
The problem is relatively simple. We just need to loop through the array once and keep track of the count of negative numbers. If the count is even, the product is going to be positive. If the count is odd, the sign is negative. We also need to check if the array has a zero element. If yes, return 0.
Let's translate the above algorithm into code:
class Solution:
def arraySign(self, nums: List[int]) -> int:
negative_count = 0
for num in nums:
if num == 0:
return 0
elif num < 0:
negative_count += 1
if negative_count % 2 == 0:
return 1
else:
return -1
Here, we're using a class-based solution. The arraySign function takes in an array of integers and returns an integer based on the prodct sign. We initialize negative_count to 0 and loop through the array. If we find a zero element, we return 0. Otherwise, we check if the element is negative and increment negative_count. After the loop, we check the count of negative numbers and return 1 or -1 depending on whether the count is even or odd, respectively.
The time complexity of this solution is O(n) and the space complexity is O(1), as we're only using a constant amount of memory.
Let's test the code on some examples:
Example 1:
Input: nums = [0, 2, -2, -3, 0] Output: 0
Explanation: The product is 0 because the array contains a 0 element.
Example 2:
Input: nums = [1, 2, 3, -4, -5] Output: -1
Explanation: The product is negative because there are 2 negative elements.
Example 3:
Input: nums = [2, -2, 2, -2, 2] Output: 1
Explanation: The product is positive because there are an even number of negative elements.
The solution works correctly for all the test cases.
Sign Of The Product Of An Array Solution Code
1