DEV Community

Ganesh K S
Ganesh K S

Posted on

Left Rotate array by K elements using reverse approach

Given array

const arr=[1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

Left Rotate array by 2 elements , Output will be ---

arr = [3,4,5,6,1,2]
Enter fullscreen mode Exit fullscreen mode

This problem can be solve with reverse array approach easily

  • First devide the array with given K elements to rotate
  • In our case K is 2

Image description

  • Reverse the corresponding devision of elements
  • So after reversing the array will be

Image description

  • Now reverse the whole array that will give you the output
  • After reversing whole array the output will be

Image description

Implementation in Code level

let arr=[1,2,3,4,5,6]
let k=2

function reverseArray(arr,start,end){
    while(start<end){
        [arr[start],arr[end]]=[arr[end],arr[start]];
        start++;
        end--;
    }

    return arr;
}

//this will be the first step to reverse the first half
let reversedFirstHalf=reverseArray(arr,0,k-1)

//this will be the second step to reverse the second half
let reversedSecondHalf=reverseArray(reversedFirstHalf,k,arr.length-1)

//After reversing the whole array
let rotateArrayOutput = reverseArray(reversedSecondHalf,0,arr.length-1)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)