Last Updated: 10 Mar, 2021

Rotate array

Easy
Asked in companies
Deutsche BankIBMSalesforce

Problem statement

Given an array 'arr' with 'n' elements, the task is to rotate the array to the left by 'k' steps, where 'k' is non-negative.


Example:
'arr '= [1,2,3,4,5]
'k' = 1  rotated array = [2,3,4,5,1]
'k' = 2  rotated array = [3,4,5,1,2]
'k' = 3  rotated array = [4,5,1,2,3] and so on.
Input Format:
The first line contains an integer 'n' representing the size of the array.

The second line contains 'n' space-separated integers representing the elements of the array.

The last line contains an integer 'k' representing the number of times the array has to be rotated in the left direction. 
Output Format:
The output contains 'n' space-separated integers representing the Rotated array elements.
Note:-
You don’t need to print anything. Just implement the given function.

Approaches

01 Approach

  • We rotate the array ‘k’ times where in each iteration, we rotate the array by 1.
  • Rotating the array once can be done by changing ‘arr’[i] to ‘arr’[i+1] and appending the first character to the end.

02 Approach

  • We note that rotating an Array K times is just placing the first K elements at the end and bringing forward rest of the elements.
  • So we store the first K elements in a temporary array.
  • We then bring the remaining N - K elements at the front by moving each of them K places ahead.
  • Finally we append the initial first K elements at the end to get the rotated Array.