DEV Community

Ganesh K S
Ganesh K S

Posted on

1

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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more