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.
1function arraySign(nums) {
2 let negativeCount = 0;
3 for (let num of nums) {
4 if (num === 0) return 0;
5 if (num < 0) negativeCount++;
6 }
7 return negativeCount % 2 === 0 ? 1 : -1;
8}
9
10console.log(arraySign([-1, -2, -3, -4, 3, 2, 1]));
The JavaScript solution iterates over the array elements. It checks for zeros immediately returning zero if found, otherwise it checks the number of negatives.
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
public class Solution {
public static int ArraySign(int[] nums) {
int sign = 1;
foreach (int num in nums) {
if (num == 0) return 0;
if (num < 0) sign *= -1;
}
return sign;
}
public static void Main() {
int[] nums = {-1, -2, -3, -4, 3, 2, 1};
Console.WriteLine(ArraySign(nums));
}
}
This C# code utilizes a sign flipping logic guided by loop-over methods to incrementally adjust result sign.