GeeksforGeeks App
Open App
Browser
Continue

Print left rotation of array in O(n) time and O(1) space

Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations?

Examples :

```Input :
arr[] = {1, 3, 5, 7, 9}
k1 = 1
k2 = 3
k3 = 4
k4 = 6
Output :
3 5 7 9 1
7 9 1 3 5
9 1 3 5 7
3 5 7 9 1

Input :
arr[] = {1, 3, 5, 7, 9}
k1 = 14
Output :
9 1 3 5 7```

We have discussed a solution in the below post.
Quickly find multiple left rotations of an array | Set 1

Method I: The solution discussed above requires extra space. In this post, an optimized solution is discussed that doesn’t require extra space.

Implementation:

C++

 `// C++ implementation of left rotation of``// an array K number of times``#include ``using` `namespace` `std;` `// Function to leftRotate array multiple times``void` `leftRotate(``int` `arr[], ``int` `n, ``int` `k)``{``    ``/* To get the starting point of rotated array */``    ``int` `mod = k % n;` `    ``// Prints the rotated array from start position``    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << (arr[(mod + i) % n]) << ``" "``;` `    ``cout << ``"\n"``;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 1, 3, 5, 7, 9 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``int` `k = 2;``  ` `      ``// Function Call``    ``leftRotate(arr, n, k);` `    ``k = 3;``  ` `      ``// Function Call``    ``leftRotate(arr, n, k);` `    ``k = 4;``  ` `      ``// Function Call``    ``leftRotate(arr, n, k);` `    ``return` `0;``}`

Java

 `// JAVA implementation of left rotation``// of an array K number of times``import` `java.util.*;``import` `java.lang.*;``import` `java.io.*;` `class` `arr_rot {``    ``// Function to leftRotate array multiple``    ``// times``    ``static` `void` `leftRotate(``int` `arr[], ``int` `n, ``int` `k)``    ``{``        ``/* To get the starting point of``        ``rotated array */``        ``int` `mod = k % n;` `        ``// Prints the rotated array from``        ``// start position``        ``for` `(``int` `i = ``0``; i < n; ++i)``            ``System.out.print(arr[(i + mod) % n] + ``" "``);` `        ``System.out.println();``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``1``, ``3``, ``5``, ``7``, ``9` `};``        ``int` `n = arr.length;` `        ``int` `k = ``2``;``      ` `          ``// Function Call``        ``leftRotate(arr, n, k);` `        ``k = ``3``;``      ` `          ``// Function Call``        ``leftRotate(arr, n, k);` `        ``k = ``4``;``      ` `          ``// Function Call``        ``leftRotate(arr, n, k);``    ``}``}` `// This code is contributed by Sanjal`

Python

 `# Python implementation of left rotation of``# an array K number of times` `# Function to leftRotate array multiple times`  `def` `leftRotate(arr, n, k):` `    ``# To get the starting point of rotated array``    ``mod ``=` `k ``%` `n``    ``s ``=` `""` `    ``# Prints the rotated array from start position``    ``for` `i ``in` `range``(n):``        ``print` `str``(arr[(mod ``+` `i) ``%` `n]),``    ``print``    ``return`  `# Driver code``arr ``=` `[``1``, ``3``, ``5``, ``7``, ``9``]``n ``=` `len``(arr)``k ``=` `2` `# Function Call``leftRotate(arr, n, k)` `k ``=` `3` `# Function Call``leftRotate(arr, n, k)` `k ``=` `4` `# Function Call``leftRotate(arr, n, k)` `# This code is contributed by Sachin Bisht`

C#

 `// C# implementation of left``// rotation of an array K``// number of times``using` `System;` `class` `GFG {` `    ``// Function to leftRotate``    ``// array multiple times``    ``static` `void` `leftRotate(``int``[] arr, ``int` `n, ``int` `k)``    ``{``        ``// To get the starting``        ``// point of rotated array``        ``int` `mod = k % n;` `        ``// Prints the rotated array``        ``// from start position``        ``for` `(``int` `i = 0; i < n; ++i)``            ``Console.Write(arr[(i + mod) % n] + ``" "``);` `        ``Console.WriteLine();``    ``}` `    ``// Driver Code``    ``static` `public` `void` `Main()``    ``{``        ``int``[] arr = { 1, 3, 5, 7, 9 };``        ``int` `n = arr.Length;` `        ``int` `k = 2;``      ` `          ``// Function Call``        ``leftRotate(arr, n, k);` `        ``k = 3;``      ` `          ``// Function Call``        ``leftRotate(arr, n, k);` `        ``k = 4;``      ` `          ``// Function Call``        ``leftRotate(arr, n, k);``    ``}``}` `// This code is contributed by m_kit`

PHP

 ``

Javascript

 ``

Output

```5 7 9 1 3
7 9 1 3 5
9 1 3 5 7 ```

Time Complexity: O(N), as we are using a loop to traverse N times.
Auxiliary Space: O(1), as we are not using any extra space.

Method II: In the below implementation we will use Standard Template Library (STL) which will be making the solution more optimize and easy to Implement.

Implementation:

C++

 `// C++ Implementation For Print Left Rotation Of Any Array K``// Times` `#include ``#include ``using` `namespace` `std;``// Function For The k Times Left Rotation``void` `leftRotate(``int` `arr[], ``int` `k, ``int` `n)``{` `    ``// Stl function rotates takes three parameters - the``    ``// beginning,the position by which it should be rotated``    ``// ,the end address of the array``      ``// The below function will be rotating the array left    ``    ``// in linear time (k%arraySize) times``    ``rotate(arr, arr + (k % n), arr + n);``    ` `      ``// Print the rotated array from start position``    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << arr[i] << ``" "``;``    ``cout << ``"\n"``;``}``// Driver program``int` `main()``{``    ``int` `arr[] = { 1, 3, 5, 7, 9 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``int` `k = 2;``  ` `      ``// Function Call``    ``leftRotate(arr, k, n);`  `    ``return` `0;``}`

Java

 `// Java implementation for print left``// rotation of any array K times``import` `java.io.*;``import` `java.util.*;` `class` `GFG{``    ` `// Function for the k times left rotation``static` `void` `leftRotate(Integer arr[], ``int` `k,``                                      ``int` `n)``{``  ` `     ``// In Collection class rotate function``     ``// takes two parameters - the name of``     ``// array and the position by which it``     ``// should be rotated``     ``// The below function will be rotating``     ``// the array left  in linear time``     ` `     ``// Collections.rotate()rotate the``     ``// array from right hence n-k``    ``Collections.rotate(Arrays.asList(arr), n - k);``    ` `    ``// Print the rotated array from start position``    ``for``(``int` `i = ``0``; i < n; i++)``        ``System.out.print(arr[i] + ``" "``);``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``Integer arr[] = { ``1``, ``3``, ``5``, ``7``, ``9` `};``    ``int` `n = arr.length;``    ``int` `k = ``2``;``    ` `    ``// Function call``    ``leftRotate(arr, k, n);``}``}` `// This code is contributed by chahattekwani71`

Python3

 `# Python3 implementation to print left``# rotation of any array K times``from` `collections ``import` `deque` `# Function For The k Times Left Rotation``def` `leftRotate(arr, k, n):``    ` `    ``# The collections module has deque class``    ``# which provides the rotate(), which is``    ``# inbuilt function to allow rotation``    ``arr ``=` `deque(arr)``    ` `    ``# using rotate() to left rotate by k``    ``arr.rotate(``-``k)``    ``arr ``=` `list``(arr)``    ` `    ``# Print the rotated array from``    ``# start position``    ``for` `i ``in` `range``(n):``        ``print``(arr[i], end ``=` `" "``)` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``      ` `    ``arr ``=` `[ ``1``, ``3``, ``5``, ``7``, ``9` `]``    ``n ``=` `len``(arr)``    ``k ``=` `2``  ` `    ``# Function Call``    ``leftRotate(arr, k, n)` `# This code is contributed by math_lover`

C#

 `// C# program for the above approach``using` `System;` `class` `GFG``{``    ``static` `void` `leftRotate(``int``[] arr, ``int` `d,``                           ``int` `n)``    ``{``        ``for` `(``int` `i = 0; i < d; i++)``            ``leftRotatebyOne(arr, n);``    ``}`` ` `    ``static` `void` `leftRotatebyOne(``int``[] arr, ``int` `n)``    ``{``        ``int` `i, temp = arr[0];``        ``for` `(i = 0; i < n - 1; i++)``            ``arr[i] = arr[i + 1];`` ` `        ``arr[n - 1] = temp;``    ``}`` ` `    ``/* utility function to print an array */``    ``static` `void` `printArray(``int``[] arr, ``int` `size)``    ``{``        ``for` `(``int` `i = 0; i < size; i++)``            ``Console.Write(arr[i] + ``" "``);``    ``}` `// Driver Code``public` `static` `void` `Main()``{``    ``int``[] arr = { 1, 3, 5, 7, 9 };``    ``int` `n = arr.Length;``    ``int` `k = 2;``    ` `    ``// Function call``    ``leftRotate(arr, k, n);``    ``printArray(arr, n);``}``}` `// This code is contributed by avijitmondal1998.`

Javascript

 ``

Output

`5 7 9 1 3 `

Note: the array itself gets updated after the rotation.

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

Method III(Using Reversal):

To left rotate an array by “k” units we will perform 3 simple reversals-

• Reverse the first “k” elements
• Reverse the last “n-k” elements where n is the size of the array
• Reverse the whole array

Code-

C++

 `// C++ Implementation For Print Left Rotation Of Any Array K``// Times` `#include ``#include ``using` `namespace` `std;``// Function For The k Times Left Rotation``void` `leftRotate(``int` `arr[], ``int` `k, ``int` `n)``{` `    ``reverse(arr,arr+k);``    ``reverse(arr+k,arr+n);``    ``reverse(arr,arr+n);``    ` `      ``// Print the rotated array from start position``    ``for` `(``int` `i = 0; i < n; i++)``        ``cout << arr[i] << ``" "``;``    ``cout << ``"\n"``;``}``// Driver program``int` `main()``{``    ``int` `arr[] = { 1, 3, 5, 7, 9 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``int` `k = 2;``  ` `      ``// Function Call``    ``leftRotate(arr, k, n);`  `    ``return` `0;``}`

Java

 `import` `java.util.*;` `public` `class` `Main {` `    ``// Function for k times left rotation``    ``public` `static` `void` `leftRotate(``int``[] arr, ``int` `k)``    ``{``      ` `        ``// Reverse the first k elements``        ``reverseArray(arr, ``0``, k - ``1``);``      ` `        ``// Reverse the remaining n-k elements``        ``reverseArray(arr, k, arr.length - ``1``);``      ` `        ``// Reverse the entire array``        ``reverseArray(arr, ``0``, arr.length - ``1``);` `        ``// Print the rotated array from start position``        ``String result = Arrays.toString(arr).replaceAll(``"\\[|\\]|,|\\s"``, ``" "``);``        ``System.out.println(result);``    ``}` `    ``// Helper function to reverse a section of an array from start to end (inclusive)``    ``public` `static` `void` `reverseArray(``int``[] arr, ``int` `start, ``int` `end) {``        ``while` `(start < end) {``            ``int` `temp = arr[start];``            ``arr[start] = arr[end];``            ``arr[end] = temp;``            ``start++;``            ``end--;``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args) {``        ``int``[] arr = {``1``, ``3``, ``5``, ``7``, ``9``};``        ``int` `k = ``2``;` `        ``// Function Call``        ``leftRotate(arr, k);``    ``}``}`

Python3

 `# Function for k times left rotation``def` `leftRotate(arr, k):``    ``# Reverse the first k elements``    ``arr ``=` `reverseArray(arr, ``0``, k ``-` `1``)``    ``# Reverse the remaining n-k elements``    ``arr ``=` `reverseArray(arr, k, ``len``(arr) ``-` `1``)``    ``# Reverse the entire array``    ``arr ``=` `reverseArray(arr, ``0``, ``len``(arr) ``-` `1``)` `    ``# Print the rotated array from start position``    ``print``(``" "``.join(``map``(``str``,arr)))` `# Helper function to reverse a section of an array from start to end (inclusive)``def` `reverseArray(arr, start, end):``    ``while` `start < end:``        ``temp ``=` `arr[start]``        ``arr[start] ``=` `arr[end]``        ``arr[end] ``=` `temp``        ``start ``+``=` `1``        ``end ``-``=` `1``    ``return` `arr` `# Driver code``arr ``=` `[``1``, ``3``, ``5``, ``7``, ``9``]``k ``=` `2``  ` `# Function Call``leftRotate(arr, k)`

C#

 `// C# Implementation For Print Left Rotation Of Any Array K``// Times``using` `System;``using` `System.Collections.Generic;` `class` `Program``{``  ` `    ``// Driver program``    ``static` `void` `Main(``string``[] args)``    ``{``        ``int``[] arr = { 1, 3, 5, 7, 9 };``        ``int` `n = arr.Length;``        ``int` `k = 2;``        ``leftRotate(arr, k, n);``        ``Console.ReadKey();``    ``}` `    ``// Function For The k Times Left Rotation``    ``static` `void` `leftRotate(``int``[] arr, ``int` `k, ``int` `n)``    ``{``        ``Array.Reverse(arr, 0, k);``        ``Array.Reverse(arr, k, n - k);``        ``Array.Reverse(arr, 0, n);` `        ``// Print the rotated array from start position``        ``for` `(``int` `i = 0; i < n; i++)``            ``Console.Write(arr[i] + ``" "``);``        ``Console.WriteLine();``    ``}``}``// This code is contributed by Tapesh(tapeshdua420)`

Javascript

 `// Function for k times left rotation``function` `leftRotate(arr, k) {``    ``// Reverse the first k elements``    ``arr = reverseArray(arr, 0, k - 1);``    ``// Reverse the remaining n-k elements``    ``arr = reverseArray(arr, k, arr.length - 1);``    ``// Reverse the entire array``    ``arr = reverseArray(arr, 0, arr.length - 1);` `    ``// Print the rotated array from start position``    ``console.log(arr.join(``" "``));``}` `// Helper function to reverse a section of an array from start to end (inclusive)``function` `reverseArray(arr, start, end) {``    ``while` `(start < end) {``        ``let temp = arr[start];``        ``arr[start] = arr[end];``        ``arr[end] = temp;``        ``start++;``        ``end--;``    ``}``    ``return` `arr;``}` `// Driver code``let arr = [1, 3, 5, 7, 9 ];``let n = arr.length;``let k = 2;``  ` `// Function Call``leftRotate(arr, k, n);`

Output

`5 7 9 1 3 `

Note: the array itself gets updated after the rotation.

Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.

This article is contributed by Sridhar Babu and improved by Geetansh Sahni. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up