Here is the problem description - https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem
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.
I wanted to get some feedback on my solution for this problem, it's a task in the Hackerrank Cracking the Coding Interview series. I am pretty sure the code is working fine, as it passes 7 of the 9 test cases, but is getting timed-out for the last two cases, since these cases are unknown, I wanted to get some expert feedback, as how can I optimize this code.
<?php
//$handle = fopen ("input_leftR.txt","r");
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d %d",$n,$k); //n and k values are available from here
$a_temp = fgets($handle);
$a = explode(" ",$a_temp);
array_walk($a,'intval');
//My Code from below
$i; $j; $temp;
if($n<0 || $n>1000000 || $k<0|| $k>1000000 || count($a) <=0)
exit;
for($i=0; $i<$k%$n; $i++){
//for($i=0; $i<$k; $i++){
for($j=0; $j<$n-1; $j++){
$temp = $a[$j];
$a[$j] = $a[$j+1];
$a[$j+1] = $temp;
}
}
//array_walk($a,'intval');
//print implode(" ", $a);
/*foreach($a as $key=>$value){
printf("%d", $value);
if($key<$n-1)
printf(" ");
}*/
for($i=0;$i<$n;$i++){
printf("%d", $a[$i]);
if($i<$n-1)
printf(" ");
}
?>