Last Updated: 17 May, 2022

Left Rotate an Array by One

Easy
Asked in companies
Tekion CorpCredex Technology

Problem statement

Given an array 'arr' containing 'n' elements, rotate this array left once and return it.


Rotating the array left by one means shifting all elements by one place to the left and moving the first element to the last position in the array.


Example:
Input: 'a' = 5, 'arr' = [1, 2, 3, 4, 5]

Output: [2, 3, 4, 5, 1]

Explanation: We moved the 2nd element to the 1st position, and 3rd element to the 2nd position, and 4th element to the 3rd position, and the 5th element to the 4th position, and move the 1st element to the 5th position.
Input Format :
The first line will contain a single integer 'n', the size of the array ‘arr’

The second line will contain ‘n’ integers representing the array elements.
Output format :
The output contains all elements of the rotated array separated by space.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.

Approaches

01 Approach

We can create a temporary array ‘rotatedArr’and store the ith element from 1 to N-1 from ‘ARR’ to i-1 the position in ‘rotatedArr’ and we store 0th element from ‘ARR’ to (n-1)th position in ‘rotatedArr’ and return ‘rotatedArr’.

 

The steps are as follows:-

  1. Create a 'rotatedArr' of size 'N', where ‘N’ is the size of ‘ARR’.
  2. Now store ith value (1 <= i <= n-1) of 'Arr' at (i-1)th position in 'rotatedArr'.
  3. Store the 0th value of 'ARR' at (N-1)th position in 'rotatedArr'.
  4. Return the ‘rotatedArr’.

02 Approach

We can store the first element of ‘arr’ in a temporary variable ‘temp’ and move each element ‘i’ where 1<= i <= ‘n’-1 to (i-1)th place formally speaking arr[i] = arr[i+1]. And replace (n-1)th element with the value of ‘temp’. In this way, our array will be rotated without using any extra space.

 

The steps are as follows:-

  1. Create a temporary variable 'firstElement' and store the value of  'arr[0]' in it.
  2. Now replace value at i with value at (i+1)th position in the array where 0<=i<=n-2.
  3. Store the 0th value of 'arr' at (n-1)th using the 'firstElement'.
  4. Return the 'arr'.