Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Rotate Array By One
Next article icon

Rotate Array By One

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array, the task is to cyclically right-rotate the array by one. 

Examples:  

Input: arr[] = [1, 2, 3, 4, 5]
Output: [5, 1, 2, 3, 4]

Input: arr[] = [2, 3, 4, 5, 1]
Output: [1, 2, 3, 4, 5]

Table of Content

  • Shifting Each Element - O(n) Time and O(1) Space
  • Using Two Pointers - O(n) Time and O(1) Space
  • Reversing the Array - O(n) Time and O(1) Space

Shifting Each Element - O(n) Time and O(1) Space

The basic idea is to store the last element in a temp variable and shift every other element one position ahead. After shifting, update the first element with value stored in temp.

C++14
#include <iostream> #include<vector> using namespace std;  void rotate(vector<int> &arr) {   int n = arr.size();        // store the last element in a variable     int lastElement = arr[n-1];      // assign every value by its predecessor     for (int i = n - 1; i > 0; i--) {         arr[i] = arr[i - 1];     }      // first element will be assigned by last element     arr[0] = lastElement; }  int main() {     vector<int> arr = {1, 2, 3, 4, 5 };      rotate(arr);     for (int i = 0; i < arr.size(); i++)         cout << arr[i] << ' ';      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  void rotate(int arr[], int n) {        // store the last element in a variable     int lastElement = arr[n-1];      // assign every value by its predecessor     for (int i = n - 1; i > 0; i--) {         arr[i] = arr[i - 1];     }      // first element will be assigned by last element     arr[0] = lastElement; }  int main() {     int arr[] = {1, 2, 3, 4, 5};     int n = sizeof(arr) / sizeof(arr[0]);      rotate(arr, n);     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);      return 0; } 
Java
import java.util.Arrays;  class GfG {     static void rotate(int[] arr) {         // store the last element in a variable         int lastElement = arr[arr.length - 1];          // assign every value by its predecessor         for (int i = arr.length - 1; i > 0; i--) {             arr[i] = arr[i - 1];         }          // first element will be assigned by last element         arr[0] = lastElement;     }      public static void main(String[] args) {         int[] arr = {1, 2, 3, 4, 5};          rotate(arr);         System.out.println(Arrays.toString(arr));     } } 
Python
def rotate(arr):        # store the last element in a variable     lastElement = arr[-1]      # assign every value by its predecessor     for i in range(len(arr) - 1, 0, -1):         arr[i] = arr[i - 1]      # first element will be assigned by last element     arr[0] = lastElement  if __name__ == "__main__":   arr = [1, 2, 3, 4, 5]   rotate(arr)   for i in range(0, len(arr)):     print(arr[i], end=' ') 
C#
using System;  class GfG {     static void Rotate(int[] arr) {                // store the last element in a variable         int lastElement = arr[arr.Length - 1];          // assign every value by its predecessor         for (int i = arr.Length - 1; i > 0; i--) {             arr[i] = arr[i - 1];         }          // first element will be assigned by last element         arr[0] = lastElement;     }      static void Main() {         int[] arr = {1, 2, 3, 4, 5};          Rotate(arr);         Console.WriteLine(string.Join(" ", arr));     } } 
JavaScript
function rotate(arr) {     // store the last element in a variable     const lastElement = arr[arr.length - 1];      // assign every value by its predecessor     for (let i = arr.length - 1; i > 0; i--) {         arr[i] = arr[i - 1];     }      // first element will be assigned by last element     arr[0] = lastElement; }  // Driver Code const arr = [1, 2, 3, 4, 5]; rotate(arr); console.log(arr); 

Output
5 1 2 3 4 

Time Complexity: O(n), as we need to iterate through all the elements. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are using constant space.

Using Two Pointers - O(n) Time and O(1) Space

We can use two pointers, As we know in cyclic rotation we will bring last element to first and shift rest in forward direction, we can do this by swapping every element with last element till we get to the last point.

C++14
#include <iostream> #include<vector> using namespace std;  void rotate(vector<int> &arr) { 	int n=arr.size();        // i and j pointing to first and last     // element respectively     int i = 0, j = n - 1;     while (i != j) {         swap(arr[i], arr[j]);         i++;     } }  int main() {  	vector<int> arr = {1, 2, 3, 4, 5 };  	int i;     rotate(arr);     for (i = 0; i < arr.size(); i++)         cout << arr[i] << " ";      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  void rotate(int *arr, int n) {        // i and j pointing to first and last     // element respectively     int i = 0, j = n - 1;     while (i != j) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;         i++;     } }  int main() {     int arr[] = {1, 2, 3, 4, 5};     int n = sizeof(arr) / sizeof(arr[0]);     rotate(arr, n);     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);     return 0; } 
Java
import java.util.Arrays;  class GfG {     static void rotate(int[] arr) {                // i and j pointing to first and last         // element respectively         int i = 0, j = arr.length - 1;         while (i != j) {             int temp = arr[i];             arr[i] = arr[j];             arr[j] = temp;             i++;         }     }      public static void main(String[] args) {         int[] arr = {1, 2, 3, 4, 5};         rotate(arr);         System.out.println(Arrays.toString(arr));     } } 
Python
def rotate(arr):        # i and j pointing to first and last     # element respectively     i, j = 0, len(arr) - 1     while i != j:         arr[i], arr[j] = arr[j], arr[i]         i += 1  if __name__ == "__main__":   arr = [1, 2, 3, 4, 5]   rotate(arr)   for i in range(0, len(arr)):     print(arr[i], end=' ') 
C#
using System;  class GfG {     static void Rotate(int[] arr) {                // i and j pointing to first and last         // element respectively         int i = 0, j = arr.Length - 1;         while (i != j) {             int temp = arr[i];             arr[i] = arr[j];             arr[j] = temp;             i++;         }     }      static void Main() {         int[] arr = {1, 2, 3, 4, 5};         Rotate(arr);         Console.WriteLine(string.Join(" ", arr));     } } 
JavaScript
function rotate(arr) {      // i and j pointing to first and last     // element respectively     let i = 0, j = arr.length - 1;     while (i !== j) {         [arr[i], arr[j]] = [arr[j], arr[i]];         i++;     } }  // Driver Code let arr = [1, 2, 3, 4, 5]; rotate(arr); console.log(arr); 

Output
5 1 2 3 4 

Time Complexity: O(n), as we need to iterate through all the elements. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are using constant space.

Reversing the Array - O(n) Time and O(1) Space

We can use Reversal Algorithm also, reverse first n-1 elements and then whole array which will result into one right rotation.

C++14
#include <iostream> #include<vector> using namespace std;  void rotate(vector<int> &arr) {   int n = arr.size();        // Reverse the first n-1 terms     int i, j;     for (i = 0, j = n - 2; i < j; i++, j--) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;     }        // Reverse the entire array     for (i = 0, j = n - 1; i < j; i++, j--) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;     } }  int main() {     vector<int> arr = {1, 2, 3, 4, 5 };     int i, j;     rotate(arr);     for (i = 0; i < arr.size(); i++)         cout << arr[i] << " ";      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  void rotate(int *arr, int n) {        // Reverse the first n-1 terms     int i, j;     for (i = 0, j = n - 2; i < j; i++, j--) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;     }          // Reverse the entire array     for (i = 0, j = n - 1; i < j; i++, j--) {         int temp = arr[i];         arr[i] = arr[j];         arr[j] = temp;     } }  int main() {     int arr[] = {1, 2, 3, 4, 5};     int n = sizeof(arr) / sizeof(arr[0]);     rotate(arr, n);     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);     return 0; } 
Java
import java.util.Arrays;  class GfG {      static void rotate(int[] arr) {         int n = arr.length;                 // Reverse the first n-1 terms         for (int i = 0, j = n - 2; i < j; i++, j--) {             int temp = arr[i];             arr[i] = arr[j];             arr[j] = temp;         }                  // Reverse the entire array         for (int i = 0, j = n - 1; i < j; i++, j--) {             int temp = arr[i];             arr[i] = arr[j];             arr[j] = temp;         }     }      public static void main(String[] args) {         int[] arr = {1, 2, 3, 4, 5};         rotate(arr);         System.out.println(Arrays.toString(arr));     } } 
Python
def rotate(arr):     n = len(arr)          # Reverse the first n-1 terms     i, j = 0, n - 2     while i < j:         arr[i], arr[j] = arr[j], arr[i]         i += 1         j -= 1          # Reverse the entire array     i, j = 0, n - 1     while i < j:         arr[i], arr[j] = arr[j], arr[i]         i += 1         j -= 1  if __name__ == "__main__":   arr = [1, 2, 3, 4, 5]   rotate(arr)   for i in range(0, len(arr)):     print(arr[i], end=' ') 
C#
using System;  class GfG {     static void Rotate(int[] arr) {         int n = arr.Length;                // Reverse the first n-1 terms         for (int i = 0, j = n - 2; i < j; i++, j--) {             int temp = arr[i];             arr[i] = arr[j];             arr[j] = temp;         }                  // Reverse the entire array         for (int i = 0, j = n - 1; i < j; i++, j--) {             int temp = arr[i];             arr[i] = arr[j];             arr[j] = temp;         }     }      static void Main() {         int[] arr = {1, 2, 3, 4, 5};         Rotate(arr);         Console.WriteLine(string.Join(" ", arr));     } } 
JavaScript
function rotate(arr) {     const n = arr.length;          // Reverse the first n-1 terms     for (let i = 0, j = n - 2; i < j; i++, j--) {         [arr[i], arr[j]] = [arr[j], arr[i]];     }          // Reverse the entire array     for (let i = 0, j = n - 1; i < j; i++, j--) {         [arr[i], arr[j]] = [arr[j], arr[i]];     } }  // Driver Code const arr = [1, 2, 3, 4, 5]; rotate(arr); console.log(arr); 

Output
5 1 2 3 4 

Time Complexity: O(n), as we are reversing the array. Where n is the number of elements in the array.
Auxiliary Space: O(1), as we are using constant space.


Next Article
Rotate Array By One

K

kartik
Improve
Article Tags :
  • DSA
  • Arrays
  • Basic Coding Problems
  • rotation
Practice Tags :
  • Arrays

Similar Reads

    Rotate bits of a number
    Given a 32-bit integer n and an integer d, rotate the binary representation of n by d positions in both left and right directions. After each rotation, convert the result back to its decimal representation and return both values in an array as [left rotation, right rotation].Note: A rotation (or cir
    7 min read
    Rotate an Array by d - Counterclockwise or Left
    Given an array of integers arr[] of size n, the task is to rotate the array elements to the left by d positions.Examples:Input: arr[] = {1, 2, 3, 4, 5, 6}, d = 2Output: {3, 4, 5, 6, 1, 2}Explanation: After first left rotation, arr[] becomes {2, 3, 4, 5, 6, 1} and after the second rotation, arr[] bec
    15+ min read
    Rotate an Array - Clockwise or Right
    Rotations in the array is defined as the process of rearranging the elements in an array by shifting each element to a new position. This is mostly done by rotating the elements of the array clockwise or counterclockwise.Table of ContentTypes of Rotations in ArrayHow to implement rotations in an arr
    15+ min read
    Rotate Matrix Clockwise by 1
    Given a square matrix, the task is to rotate its elements clockwise by one step.Examples:Input 1 2 34 5 6 7 8 9Output: 4 1 27 5 3 8 9 6Input: 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12The idea is to use nested loops to move elements in four directions (right
    9 min read
    Rotate a Matrix by 180 degree
    Given a square matrix, the task is to turn it by 180 degrees. Note that when we rotate a matrix by 180 degree, clockwise and anticlockwise both give same results. Examples: Input: mat[][] = [[1, 2, 3] [4, 5, 6] [7, 8, 9]]Output: [9, 8, 7] [6, 5, 4] [3, 2, 1]Input: mat[][] = [[1, 2, 3, 4], [5, 6, 7,
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences