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.
1public class Main {
2 public static int arraySign(int[] nums) {
3 int negativeCount = 0;
4 for (int num : nums) {
5 if (num == 0) return 0;
6 if (num < 0) negativeCount++;
7 }
8 return (negativeCount % 2 == 0) ? 1 : -1;
9 }
10
11 public static void main(String[] args) {
12 int[] nums = {-1,-2,-3,-4,3,2,1};
13 System.out.println(arraySign(nums));
14 }
15}
The Java solution involves looping through the array with an enhanced for loop. Upon finding a zero, it returns zero. Otherwise, it calculates based on the sign of the product determined by the count of negative elements.
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
Python uses a similar pattern, where an initialized 'sign' is multiplied by -1 for every negative, zero results in an immediate 0 return.