Here is the problem description: https://www.hackerrank.com/challenges/ctci-array-left-rotation
A left rotation operation on an array of size \$n\$ shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array \$[1,2,3,4,5]\$, then the array would become \$[3,4,5,1,2]\$.
Given an array of \$n\$ integers and a number, \$d\$, perform \$d\$ left rotations on the array. Then print the updated array as a single line of space-separated integers.
My code passes all test cases but is stuck on Hacker rank timeout. I want to know where is the part that takes too long to execute, in order to optimize my code.
<?php
function rotateOnce($a)
{
if ($a[0] >= 1 && $a[0] <= 1000000) {
$left = array_shift($a);
$a[] = $left;
}
return $a;
}
function checkConstrains($d, $n)
{
if ($d >= 1 && $d <= $n && $n >= 1 && $n <= 10 ^ 5)
return true;
return false;
}
// Complete the rotLeft function below.
function rotLeft($a, $d)
{
global $n;
if (checkConstrains($d, $n)) {
for ($i = 0; $i < $d; $i++) {
$a = rotateOnce($a);
}
}
return $a;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");
fscanf($stdin, "%[^\n]", $nd_temp);
$nd = explode(' ', $nd_temp);
$n = intval($nd[0]);
$d = intval($nd[1]);
fscanf($stdin, "%[^\n]", $a_temp);
$a = array_map('intval', preg_split('/ /', $a_temp, -1, PREG_SPLIT_NO_EMPTY));
$result = rotLeft($a, $d);
fwrite($fptr, implode(" ", $result) . "\n");
fclose($stdin);
fclose($fptr);