Hackerrank with PHP: Arrays Left Rotation

Got another simple Hackerrank solution! This is one of the first challenges in the arrays section dealing with left rotation. Here's the problem description:

A left rotation operation on an array 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 a of n integers and a number, d, perform d left rotations on the array. Return the updated array to be printed as a single line of space-separated integers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Complete the rotLeft function below.
function rotLeft($a, $d) {
    foreach($a as $key => $value) {
        $pos = $key - $d;
       
        if($pos < 0) {
            $pos = $pos + count($a);
        }
       
        $rotated[$pos] = $value;
    }
   
    ksort($rotated);
   
    return $rotated;
}

Hope this helps! Let me know of any questions in the comments.

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *

About Christina M. Gleason

Christina GleasonDeveloper who has been playing with websites since I was a preteen, it started with some tables and CSS creating a website about fairies (true story). Since then, I got a BS in Computer Science, and went to work on PHP-based websites and applications. I spent some time in custom frameworks, then a lot of time in custom WordPress development and Magento e-commerce. Industries I've worked in include logistics, healthcare, retirement communities, legal, spiritual, and HVAC.

I am an active knitter, and I also really enjoy scrapbooking and painting. Creativity has always been at my core, and I bring that into my daily workflow all the time. Lifting and working out is also important to me. I'm also married, have two daughters, and two rescue dogs Barlow and Sunshine.

Find me on: Ravelry | Instagram | Twitter | LinkedIn | GitHub