Sign of An Array
There is a function signFunc(x)
-
if1 is positive.x -
if-1 is negative.x -
if0 is equal to 0.x
You are given an integer array numsproductnums
Return signFunc(product)
Example 1
Output: 1
Explanation: The product of all values in the array is 144, and signFunc(144) = 1
Example 2
Output: 0
Explanation: The product of all values in the array is 0, and signFunc(0) = 0
Example 3
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] <= 100
Solution 1 - Count total number of negatives, return -1 if there are odd number of negatives, 1 otherwise, and 0 if there is atleast one 0
In this approach, instead of calculating the product of array, we will simply count the number of negative integers, if there are are odd number of
negative interegs, then the product is going to be a negative value, so we will return -110
public class SignOfArray {
static int arraySign(int[] nums) {
int totalNegatives = 0;
for(int i=0; i<nums.length; i++) {
if(nums[i] == 0) {
return 0;
}
if(nums[i] <0) {
totalNegatives++;
}
}
return totalNegatives %2 ==0 ? 1 : -1;
}
public static void main(String[] args) {
System.out.println(arraySign(new int[]{-1,-2,-3,-4,3,2,1}));
System.out.println(arraySign(new int[]{1,5,0,2,-3}));
System.out.println(arraySign(new int[]{-1,1,-1,1,-1}));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
Space complexity: O(1)
Above implementations source code can be found at