In this Left Rotation HackerRank solution, A left rotation operation on an array of size shifts each of the array’s elements unit to the left. Given an integer, , rotate the array that many steps left and return the result.
Example
After rotations, .
Function Description
Complete the rotateLeft function in the editor below.
rotateLeft has the following parameters:
- int d: the amount to rotate by
- int arr[n]: the array to rotate
Returns
- int[n]: the rotated array
Input Format
The first line contains two space-separated integers that denote , the number of integers, and , the number of left rotations to perform.
The second line contains space-separated integers that describe .
Constraints
Sample Input
5 4
1 2 3 4 5
Sample Output
5 1 2 3 4
Explanation
To perform left rotations, the array undergoes the following sequence of changes:
Left Rotation HackerRank Solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
function rotateLeft(d, arr) {
for(let i=0; i< d; i++){
let firstElement = arr.shift();
arr.push(firstElement);
}
return arr;
}
Problem Solution in C#
public static List<int> rotateLeft(int d, List<int> arr)
{
for(var i = 0; i< d; i++){
var value = arr[0];
arr.Remove(arr[0]);
arr.Add(value);
}
return arr;
}
Problem Solution in Python
def rotateLeft(d, arr):
rotated = arr[d:] + arr[:d]
return rotated
Problem Solution in C++
vector<int> rotateLeft(int d, vector<int> arr) {
// Index pattern:
// 0 1 2 3 4
// 3 4 0 1 2
int n = arr.size();
vector<int> res(n);
for (int i = 0; i < n; ++i){
if (i < d) res[i + (n - d)] = arr[i];
else res[i - d] = arr[i];
}
return res;
}