Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SabrinaMarkon/62e4414358bf2891c98c24fc34fad52c to your computer and use it in GitHub Desktop.
Save SabrinaMarkon/62e4414358bf2891c98c24fc34fad52c to your computer and use it in GitHub Desktop.
PHP array left rotation without shifts or sorts. Doesn't cause timeout on HackerRank left rotation challenge.
<?php
/*
NOTES: If $newa is not pre-filled, the function will fail
because the keys will be added out of numerical order, and also, we can't
use ksort here because the test times out for large input arrays if we
do sorts or shifts of any kind.
i.e. $newa[0] might not be in the first spot of the array for instance.
Pre-filling the $newa array makes sure that the keys are 0-($n-1) in order.
*/
function rotLeft($a, $d) {
// length of array
$n = sizeof($a);
// create new pre-filled array the same size as $a.
$newa = array_fill(0, $n, null);
for ($i = 0; $i < $n; $i++) {
// get the new key to assign the value of $a[$i] to in $newa array.
$newkey = ($i + ($n - $d)) % $n;
// assign the value of $a[$i] to the correct key in the new array $newa.
$newa[$newkey] = $a[$i];
}
return $newa;
}
// simple test
$a = [1,2,3,4,5];
$d = 4;
$newa = rotLeft($a, $d);
print_r($newa);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment