I'm posting about my solutions to the HackerRank challenges as a way to improve my learning, reinforce my knowledge, and establish an understanding of the concepts covered. If I help someone by sharing along the way, even better!
Left Rotation is one of the initial challenges with 'EASY' difficulty.
A left rotation operation on an array shifts each array element to the left. For example, if two left rotations are performed on the array [1, 2, 3, 4, 5], the array becomes [3, 4, 5, 1, 2].
Given an array a of n integers and a number, d, of left rotations in the array. Return the updated array to be printed as a single line of integers separated by spaces.
A function that returns an array of integers after the left rotations have been performed.
1 <= n <= 10 ^ 51 <= d <= n1 <= a [i] <= 10 ^ 61 2 3 4 5
4 5 1 2 3 4 function leftRotation (a , d ) {
return a .concat (a .splice (0 , d ));
}All the logic is contained in this single line, but we can divide it into three parts:
I first used .splice() to get the first d items in the a[0 - d] array. At the beginning of the challenge, the following limit is informed that defines this logic 1 <= d <= n, that is, I don't need to worry about rotating the matrix to the left more times than the items in the array.
I then used .concat() to concatenate (or merge) what's left of a, or everything after a[d], with what I separated in the first step a[0 - d].
And then I finish the function by returning this newly sorted array.
Other languages that I speak
def leftRotation (a , d )
a .rotate (d )
end def leftRotation (a , d ):
return a [a : ] + a [: a ]func leftRotation (a [] int32 , d int32 ) []int32 {
return append (a [d : ], a [: d ]... )
}def leftRotation (a : Array [Int ], d : Int ): Array [Int ] = {
return a .drop (d )++ a .take (d );
}static int leftRotation (int [] a , int d ) {
int [] rotated = new int [a .length ];
for (int i = 0 ; i < a .length ; i++ ) {
rotated[(i + a .length - d ) % a .length ] = a [i];
}
return rotated;
}function leftRotation ($a , $d ) {
return array_merge (array_splice ($a , $d , count ($a )), array_splice ($a , 0 , $d ));
}Thought: We can judge the heart of a man by his treatment of animals.