How to check if an array contains a contiguous subarray having zero-sum in PHP

1 Answer

0 votes
function hasZeroSumSubarray($arr) {
    $size = count($arr);
    
    for ($i = 0; $i < $size; $i++) {
        $sum = $arr[$i];
        $startIndex = $i;
        
        if ($sum == 0) {
            return true;
        }
        
        for ($j = $i + 1; $j < $size; $j++) {
            $sum += $arr[$j];
            $endIndex = $j;
            if ($sum == 0) {
                echo "index from: " . $startIndex . " to: " . $endIndex . "\n";
                return true;
            }
        }
    }

    return false;
}


$arr = array(8, 32, 4, -5, 1, 9);
        
$hasZeroSum = hasZeroSumSubarray($arr);

if ($hasZeroSum) {
    echo "The array contains a contiguous subarray with zero-sum" . "\n";
}
else {
    echo "The array does not contain a contiguous subarray with zero-sum" . "\n";
}





/*
run:

index from: 2 to: 4
The array contains a contiguous subarray with zero-sum

*/

 



answered Sep 8, 2023 by avibootz
...