Hacker rank - Left rotation - PHP code feedback for Timeout
Efficiency

You do a lot of manual shifting and pushing with your array. This is ok for small inputs, but as soon, as the distance $d and the size of your array $n grow, this becomes inefficient.

The main overhead however is coming from calling rotateOnce. Parameters are passed by value by default. That means the array is copied every time the function is called. You could pass it by reference:

function rotateOnce(&amp;$a) {}


or simply include the two lines in your original function:

function rotLeft($a, $d) {
    $n = count($a);

    for ($i = 0; $i &lt; $d; $i++) {
        $left = array_shift($a);
        $a[] = $left;
    }

    return $a;
}


I would guess that constraints on HackerRank mean, that you can expect values in that range and don't need to test inputs yourself.

This is now significant faster, but still slow especially for large distances $d.



That being said, I would take a look at PHP's internal array functions and think of a way, how to use them in combination to increase performance.

My naive approach would be something like this


if d is 0 or the same as the array's size, return the original
else split the array into two chunks at index $d
combine both arrays and return the result


The function could look like this Don't hover if you don't want to get spoiled:


   
 function rotLeft($a, $d) {
     if (count($a) == $d || $d === 0) {
         return $a;
     }

     $chunk1 = array_slice($a, 0, $d);
     $chunk2 = array_slice($a, $d);

     return array_merge($chunk2, $chunk1);
 }
 


For this input:

$a = range(1, 100000);
$n = count($a);
$d = 500;


… I've measured these times on my local machine*:


original: 1.8130s
optimized: 0.4294
rewritten: 0.0054s




Exponential expression vs. bitwise Operators

Your program has a flaw. It won't calculate the result correctly for large array sizes, because of this:


$n &lt;= 10 ^ 5



^ is bitwise Xor and not pow:

pow(10, 5);
10 ** 5;




Try to avoid globals

I can see, that n is an input parameter that is not part of the function's given signature. However, I would try to avoid globals and get the value manually, if needed:

$n = count($a);


You can read more about this here:


PHP global in functions

Are global variables in PHP considered bad practice? If so, why?




* macOS 10.13, I7 2.5 GHz, 16GB RAM, MAMP PHP 7.2.1