In this post, we will solve the Left Rotation HackerRank Solution. This problem (Left Rotation) is a part of the HackerRank Problem Solving series.
the array that many steps left and return the result.
Example
d = 2
arr = [1, 2, 3, 4, 5]
After 2 rotations,arr = [1, 2, 3, 4, 5] .
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
Left Rotation Hacker Rank Solution
Problem solution in Python programming:
def rotateLeft(d, arr): result = [0] * len(arr) for i in range(len(arr)): result[i - d] = arr[i] return result
Problem solution in Java programming:
public static List<Integer> rotateLeft(int d, List<Integer> arr) { int temp=0; for(int i=0;i<d;i++){ System.out.println(i); temp = arr.get(0); arr.remove(0); arr.add(temp); } return arr; }
Problem solution in JavaScript programming:
function rotateLeft(d, arr) { let newArr = []; let len = arr.length for(let i=0;i<len;i++){ let num = arr[i]; let diff = i-d; if(diff<0){ newArr[len-d+i] = num; }else{ newArr[i-d] = num } } return newArr }
Leave a Reply