Duplicate Zeros PHP Solution
class Solution {

    /**
     * @param Integer[] $arr
     * @return NULL
     */
    function duplicateZeros(&$arr) {
        $newArr = []; //Create new array
        foreach($arr as $value){
            if($value == 0){
                array_push($newArr, $value, $value); //Whenever I meet a 0 I push twice this value in the new array $newArr
            } else {
                array_push($newArr, $value); // I push only once for all the other values ($value != 0)
            }
        }
        
        $diff = (count($newArr) - 1) - (count($arr) - 1); // Calculate the difference of length between the given array $arr and the new one $newArr
        
        for($i = 0; $i < $diff; $i++){
            array_pop($newArr);  //I loop while $i < $diff to remove the extra elements in the new array
        }
        
        $arr = array_replace($arr, $newArr); //Finally I replace the given array $arr by the new one $newArr
    }
}
Comments (1)