Task 1: Product Sign
You are given an array of integers, @ints.
Write a script to return:
1if the product of all integers in the array is positive-1if the product is negative0if the product is zero
Example 1: Input: @ints = (-1, -2, -3, -4, 3, 2, 1) → Output: 1
Example 2: Input: @ints = (1, 2, 0, -2, -1) → Output: 0
Example 3: Input: @ints = (-1, -1, 1, -1, 2) → Output: -1
Method Explanation
A naive approach would compute the cumulative multiplication of all integers in the list and inspect whether the result is positive, negative, or zero. However, computing the raw product of large arrays can lead to arithmetic overflow in fixed-precision languages and wastes processing time.
Instead, we observe that the sign depends only on two factors:
- If any element in the array is
0, the product is immediately zero, allowing for early exit. - Positive numbers do not alter the overall sign.
- Each negative number flips the sign. Thus, an even count of negative numbers yields a positive product (
1), whereas an odd count yields a negative product (-1).
This runs in linear time $O(N)$ and requires $O(1)$ auxiliary memory.
Perl Solution
use v5.38;
use warnings;
use Type::Params -sigs;
use Types::Standard qw(ArrayRef Int);
signature_for product_sign => (
method => 0,
positional => [ ArrayRef [Int] ],
);
sub product_sign ($ints_ref) {
my $negative_count = 0;
for my $value (@$ints_ref) {
return 0 if $value == 0;
$negative_count++ if $value < 0;
}
return $negative_count % 2 == 0 ? 1 : -1;
}
Python Solution
def product_sign(ints: list[int]) -> int:
"""Compute the sign of the product of a list of integers."""
negative_count = 0
for value in ints:
if value == 0:
return 0
if value < 0:
negative_count += 1
return -1 if negative_count % 2 != 0 else 1