The Wayback Machine - https://web.archive.org/web/20240818163942/https://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
Open In App

Reversal algorithm for Array rotation

Last Updated : 06 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
 

Given an array arr[] of size N, the task is to rotate the array by d position to the left.

Examples: 

Input:  arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2
Output: 3, 4, 5, 6, 7, 1, 2
Explanation: If the array is rotated by 1 position to the left, 
it becomes {2, 3, 4, 5, 6, 7, 1}.
When it is rotated further by 1 position,
it becomes: {3, 4, 5, 6, 7, 1, 2}

Input: arr[] = {1, 6, 7, 8}, d = 3
Output: 8, 1, 6, 7

 

Approach: We have already discussed several methods in this post. The ways discussed there are:

  • Using another temporary array.
  • Rotating one by one.
  • Using a juggling algorithm.

Another Approach (The Reversal Algorithm): Here we will be discussing another method which uses the concept of reversing a part of array. The intuition behind the idea is mentioned below:

Intuition:

If we observe closely, we can see that a group of array elements is changing its position. For example see the following array:
arr[] = {1, 2, 3, 4, 5, 6, 7} and d = 2. The rotated array is {3, 4, 5, 6, 7, 1, 2}

The group having the first two elements is moving to the end of the array. This is like reversing the array.

  • But the issue is that if we only reverse the array, it becomes {7, 6, 5, 4, 3, 2, 1}. 
  • After rotation the elements in the chunks having the first 5 elements {7, 6, 5, 4, 3} and the last 2 elements {2, 1} should be in the actual order as of the initial array [i.e., {3, 4, 5, 6, 7} and {1, 2}]but here it gets reversed. 
  • So if those blocks are reversed again we get the desired rotated array.

So the sequence of operations is:

  • Reverse the whole array 
  • Then reverse the last ‘d’ elements and 
  • Then reverse the first (N-d) elements.

As we are performing reverse operations it is also similar to the following sequence:

  • Reverse the first ‘d’ elements
  • Reverse last (N-d) elements
  • Reverse the whole array.

Algorithm: The algorithm can be described with the help of the below pseudocode:

Pseudocode:  

Algorithm reverse(arr, start, end):
    mid = (start + end)/2
    loop from i = start to mid:
        swap (arr[i], arr[end-(mid-i+1)])

Algorithm rotate(arr, d, N):
    reverse(arr, 1, d) ;
    reverse(arr, d + 1, N);
    reverse(arr, 1, N);

Illustration:

Follow the illustration below to for  better understanding of the algorithm and intuition:

For example take the array arr[] = {1, 2, 3, 4, 5, 6, 7} and d = 2.

Array

Array

The rotated array will look like:

Rotated Array

Rotated Array

1st Step: Consider the array as a combination of two blocks. One containing the first two elements and the other containing the remaining elements as shown above.

Considered 2 blocks

Considered 2 blocks

2nd Step: Now reverse the first d elements. It becomes as shown in the image

Reverse the first K elements

Reverse the first K elements

3rd Step: Now reverse the last (N-d) elements. It become as it is shown in the below image:

Reverse the last (N-K) elements

Reverse the last (N-K) elements

4th Step: Now the array is the exact reversed form of how it should be if left shifted d times. So reverse the whole array and you will get the required rotated array.

The total array is reversed

The total array is reversed

See that the array is now the same as the rotated array.

Below is the implementation of the above approach: 
 

C++




#include <algorithm> // for reverse function
#include <iostream>  // for input/output operations
#include <vector>    // for vector container
using namespace std;
 
// Function to rotate an array by k elements to the right
void rotateArray(vector<int>& arr, int k)
{
    // Find the size of the array
    int n = arr.size();
 
    // Mod k with the size of the array
    // To handle the case where k is greater than the size of the array
    k %= n;
 
    // Reverse the entire array
    reverse(arr.begin(), arr.end());
 
    // Reverse the first k elements
    reverse(arr.begin(), arr.begin() + k);
 
    // Reverse the remaining n-k elements
    reverse(arr.begin() + k, arr.end());
}
 
int main()
{
    // Initialize the array
    vector<int> arr = { 1, 2, 3, 4, 5 };
 
    // Number of elements to rotate to the right
    int k = 2;
 
    // Call the rotateArray function to rotate the array
    rotateArray(arr, k);
 
    // Print the rotated array
    for (int i : arr) {
        cout << i << " ";
    }
 
    // Return 0 to indicate successful termination of the program
    return 0;
}


C++




// C++ program for reversal algorithm
// of array rotation
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to reverse arr[]
// from index start to end
void reverseArray(int arr[], int start, int end)
{
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
 
// Function to left rotate arr[] of size n by d
void leftRotate(int arr[], int d, int n)
{
    if (d == 0)
        return;
     
    // In case the rotating factor is
    // greater than array length
    d = d % n;
 
    reverseArray(arr, 0, d - 1);
    reverseArray(arr, d, n - 1);
    reverseArray(arr, 0, n - 1);
}
 
// Function to print an array
void printArray(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int d = 2;
 
    // Function call
    leftRotate(arr, d, N);
    printArray(arr, N);
    return 0;
}


C




// C/C++ program for reversal algorithm of array rotation
#include <stdio.h>
 
/*Utility function to print an array */
void printArray(int arr[], int size);
 
/* Utility function to reverse arr[] from start to end */
void reverseArray(int arr[], int start, int end);
 
/* Function to left rotate arr[] of size n by d */
void leftRotate(int arr[], int d, int n)
{
 
    if (d == 0)
        return;
    // in case the rotating factor is
    // greater than array length
    d = d % n;
 
    reverseArray(arr, 0, d - 1);
    reverseArray(arr, d, n - 1);
    reverseArray(arr, 0, n - 1);
}
 
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
}
 
/*Function to reverse arr[] from index start to end*/
void reverseArray(int arr[], int start, int end)
{
    int temp;
    while (start < end) {
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
 
/* Driver program to test above functions */
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int d = 2;
 
    leftRotate(arr, d, n);
    printArray(arr, n);
    return 0;
}


Java




// Java program for reversal algorithm of array rotation
import java.io.*;
 
class LeftRotate {
    /* Function to left rotate arr[] of size n by d */
    static void leftRotate(int arr[], int d)
    {
 
        if (d == 0)
            return;
 
        int n = arr.length;
        // in case the rotating factor is
        // greater than array length
        d = d % n;
        reverseArray(arr, 0, d - 1);
        reverseArray(arr, d, n - 1);
        reverseArray(arr, 0, n - 1);
    }
 
    /*Function to reverse arr[] from index start to end*/
    static void reverseArray(int arr[], int start, int end)
    {
        int temp;
        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }
 
    /*UTILITY FUNCTIONS*/
    /* function to print an array */
    static void printArray(int arr[])
    {
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
        int n = arr.length;
        int d = 2;
 
        leftRotate(arr, d); // Rotate array by d
        printArray(arr);
    }
}
/*This code is contributed by Devesh Agrawal*/


Python3




# Python program for reversal algorithm of array rotation
 
# Function to reverse arr[] from index start to end
 
 
def reverseArray(arr, start, end):
    while (start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end = end-1
 
# Function to left rotate arr[] of size n by d
 
 
def leftRotate(arr, d):
 
    if d == 0:
        return
    n = len(arr)
    # in case the rotating factor is
    # greater than array length
    d = d % n
    reverseArray(arr, 0, d-1)
    reverseArray(arr, d, n-1)
    reverseArray(arr, 0, n-1)
 
# Function to print an array
 
 
def printArray(arr):
    for i in range(0, len(arr)):
        print (arr[i],end=' ')
 
 
# Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
n = len(arr)
d = 2
 
leftRotate(arr, d)  # Rotate array by 2
printArray(arr)
 
# This code is contributed by Devesh Agrawal


C#




// C# program for reversal algorithm
// of array rotation
using System;
 
class GFG {
    /* Function to left rotate arr[]
    of size n by d */
    static void leftRotate(int[] arr, int d)
    {
 
        if (d == 0)
            return;
        int n = arr.Length;
          // in case the rotating factor is
        // greater than array length
        d = d % n;
        reverseArray(arr, 0, d - 1);
        reverseArray(arr, d, n - 1);
        reverseArray(arr, 0, n - 1);
    }
 
    /* Function to reverse arr[] from
    index start to end*/
    static void reverseArray(int[] arr, int start,
                             int end)
    {
        int temp;
        while (start < end) {
            temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }
 
    /*UTILITY FUNCTIONS*/
    /* function to print an array */
    static void printArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
        int n = arr.Length;
        int d = 2;
 
        leftRotate(arr, d); // Rotate array by 2
        printArray(arr);
    }
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP program for reversal
// algorithm of array rotation
 
/* Function to left rotate
   arr of size n by d */
function leftRotate(&$arr, $d, $n)
{
 
    if ($d == 0)
        return;
      // in case the rotating factor is
      // greater than array length
      $d = ($d % $n);
    reverseArray($arr, 0, $d - 1);
    reverseArray($arr, $d, $n - 1);
    reverseArray($arr, 0, $n - 1);
}
 
/*Function to reverse $arr
  from index start to end*/
function reverseArray(&$arr,
                       $start, $end)
{
    while ($start < $end)
    {
        $temp = $arr[$start];
        $arr[$start] = $arr[$end];
        $arr[$end] = $temp;
        $start++;
        $end--;
    }
}
 
// Function to
// print an array
function printArray($arr, $size)
{
    for ($i = 0; $i < $size; $i++)
    print $arr[$i]." ";
}
 
// Driver code
$arr = array(1, 2, 3,
             4, 5, 6, 7);
$n = sizeof($arr);
$d = 2;
 
// Function calling
leftRotate($arr, $d, $n);
printArray($arr, $n);
     
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
      // JavaScript program for reversal algorithm
      // of array rotation
 
      /*Function to reverse arr[] from index start to end*/
      function reverseArray(arr, start, end) {
        while (start < end) {
          var temp = arr[start];
          arr[start] = arr[end];
          arr[end] = temp;
          start++;
          end--;
        }
      }
 
      /* Function to left rotate arr[] of size n by d */
      function leftRotate(arr, d, n) {
        if (d == 0) return;
        // in case the rotating factor is
        // greater than array length
        d = d % n;
 
        reverseArray(arr, 0, d - 1);
        reverseArray(arr, d, n - 1);
        reverseArray(arr, 0, n - 1);
      }
 
      // Function to print an array
      function printArray(arr, size)
      {
        for (var i = 0; i < size; i++) document.write(arr[i] + " ");
      }
 
      /* Driver program to test above functions */
 
      var arr = [1, 2, 3, 4, 5, 6, 7];
      var n = arr.length;
      var d = 2;
 
      // Function calling
      leftRotate(arr, d, n);
      printArray(arr, n);
       
      // This code is contributed by rdtank.
    </script>


Output

3 4 5 6 7 1 2 

Time Complexity: O(N)
Auxiliary Space: O(1)

Another Method :-  Using C++ STL  reverse

C++




#include <algorithm> // for reverse function
#include <iostream>  // for input/output operations
#include <vector>    // for vector container
using namespace std;
 
// Function to rotate an array by k elements to the right
void rotateArray(vector<int>& arr, int k)
{
    // Find the size of the array
    int n = arr.size();
 
    // Mod k with the size of the array
    // To handle the case where k is greater than the size of the array
    k %= n;
 
    // Reverse the entire array
    reverse(arr.begin(), arr.end());
 
    // Reverse the first k elements
    reverse(arr.begin(), arr.begin() + k);
 
    // Reverse the remaining n-k elements
    reverse(arr.begin() + k, arr.end());
}
 
int main()
{
    // Initialize the array
    vector<int> arr = { 1, 2, 3, 4, 5 };
 
    // Number of elements to rotate to the right
    int k = 2;
 
    // Call the rotateArray function to rotate the array
    rotateArray(arr, k);
 
    // Print the rotated array
    for (int i : arr) {
        cout << i << " ";
    }
 
    // Return 0 to indicate successful termination of the program
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Collections;
 
public class Main {
    public static void main(String[] args)
    {
        // Initialize the array
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        arr.add(5);
        // Number of elements to rotate to the right
        int k = 2;
 
        // Call the rotateArray function to rotate the array
        rotateArray(arr, k);
 
        // Print the rotated array
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
 
    // Function to rotate an array by k elements to the
    // right
    public static void rotateArray(ArrayList<Integer> arr,
                                   int k)
    {
        // Find the size of the array
        int n = arr.size();
 
        // Mod k with the size of the array
        // To handle the case where k is greater than the
        // size of the array
        k %= n;
 
        // Reverse the entire array
        Collections.reverse(arr);
 
        // Reverse the first k elements
        for (int i = 0; i < k / 2; i++) {
            int temp = arr.get(i);
            arr.set(i, arr.get(k - i - 1));
            arr.set(k - i - 1, temp);
        }
 
        // Reverse the remaining n-k elements
        for (int i = k; i < (n + k) / 2; i++) {
            int temp = arr.get(i);
            arr.set(i, arr.get(n + k - i - 1));
            arr.set(n + k - i - 1, temp);
        }
    }
}


Python3




# Function to rotate an array by k elements to the right
def rotateArray(arr, k):
    # Find the size of the array
    n = len(arr);
 
    # Mod k with the size of the array
    # To handle the case where k is greater than the size of the array
    k %= n;
 
    # Reverse the entire array
    arr[0:n] = arr[0:n][::-1]
 
    # Reverse the first k elements
    arr[0:k] = arr[0:k][::-1]
 
    # Reverse the remaining n-k elements
    arr[k:n] = arr[k:n][::-1]
 
# Initialize the array
arr = [ 1, 2, 3, 4, 5 ];
 
# Number of elements to rotate to the right
k = 2;
 
# Call the rotateArray function to rotate the array
rotateArray(arr, k);
 
# Print the rotated array
for i in range(0,len(arr)):
    print(arr[i], end= " ");


Javascript




// Define the function to rotate an array
function rotateArray(arr, k) {
// Find the length of the array
const n = arr.length;
 
// Mod k with the length of the array
// To handle the case where k is greater than the
// length of the array
k %= n;
 
// Reverse the entire array
arr.reverse();
 
// Reverse the first k elements
for (let i = 0; i < k / 2; i++) {
const temp = arr[i];
arr[i] = arr[k - i - 1];
arr[k - i - 1] = temp;
}
 
// Reverse the remaining n-k elements
for (let i = k; i < (n + k) / 2; i++) {
const temp = arr[i];
arr[i] = arr[n + k - i - 1];
arr[n + k - i - 1] = temp;
}
}
 
// Initialize the array
const arr = [1, 2, 3, 4, 5];
 
// Number of elements to rotate to the right
const k = 2;
 
// Call the rotateArray function to rotate the array
rotateArray(arr, k);
 
// Print the rotated array
console.log(arr.join(' '));


C#




using System;
using System.Linq;
 
namespace ArrayRotation {
class Program {
    static void Main(string[] args)
    {
        // Initialize the array
        int[] arr = { 1, 2, 3, 4, 5 };
 
        // Number of elements to rotate to the right
        int k = 2;
 
        // Call the RotateArray function to rotate the array
        RotateArray(ref arr, k);
 
        // Print the rotated array
        Console.WriteLine(string.Join(" ", arr));
 
        // Wait for the user to end the program
        Console.ReadKey();
    }
 
    // Function to rotate an array by k elements to the
    // right
    static void RotateArray(ref int[] arr, int k)
    {
        // Find the size of the array
        int n = arr.Length;
 
        // Mod k with the size of the array
        // To handle the case where k is greater than the
        // size of the array
        k %= n;
 
        // Reverse the first n-k elements
        Array.Reverse(arr, 0, n - k);
 
        // Reverse the remaining k elements
        Array.Reverse(arr, n - k, k);
 
        // Reverse the entire array
        Array.Reverse(arr);
    }
}
}


Output

4 5 1 2 3 

Time Complexity: O(N)
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Python3 Program for Reversal algorithm for right rotation of an array
Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n. We can easily modify the solutions to handle lar
2 min read
Javascript Program for Reversal algorithm for right rotation of an array
Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n. We can easily modify the solutions to handle lar
2 min read
Javascript Program for Reversal algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Example : Input : arr[] = [1, 2, 3, 4, 5, 6, 7] d = 2 Output : arr[] = [3, 4, 5, 6, 7, 1, 2] Rotation of the above array by 2 will make array Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. The first 3 methods to rotate an array by
3 min read
Reversal algorithm for right rotation of an array
Given an array, right rotate it by k elements. After K=3 rotation Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} k = 3 Output: 8 9 10 1 2 3 4 5 6 7 Input: arr[] = {121, 232, 33, 43 ,5} k = 2 Output: 43 5 121 232 33 Note : In the below solution, k is assumed to be smaller than or equal to n. We can easily modify the solutions to handle lar
6 min read
Python3 Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n)Right (Or clockwise) rotate the given string by d elements (where d &lt;= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation :
3 min read
Javascript Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n)Right (Or clockwise) rotate the given string by d elements (where d &lt;= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation :
3 min read
Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n) Right (Or clockwise) rotate the given string by d elements (where d &lt;= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "
15+ min read
Modify an array by sorting after reversal of bits of each array element
Given an array arr[] consisting of N integers, the task is to modify the array by replacing each array element with the number obtained by reversing their respective binary representations and sort the modified array. Examples: Input: arr[ ] = {43, 422, 132}Output: 33 53 203Explanation: The binary representation of the array elements are {101011, 1
10 min read
Block swap algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make an array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change
15+ min read
Javascript Program for Block swap algorithm for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABl
3 min read
Python3 Program for Block swap algorithm for array rotation
Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change ABl
3 min read
XOR Linked List - Reversal of a List
Given a XOR linked list, the task is to reverse the XOR linked list. Examples: Input: 4 &lt;–&gt; 7 &lt;–&gt; 9 &lt;–&gt; 7Output: 7 &lt;–&gt; 9 &lt;–&gt; 7 &lt;–&gt; 4Explanation:Reversing the linked list modifies the XOR linked list to 7 &lt;–&gt; 9 &lt;–&gt; 7 &lt;–&gt; 4. Input: 2 &lt;-&gt; 5 &lt;-&gt; 7 &lt;-&gt; 4Output: 4 &lt;-&gt; 7 &lt;-
12 min read
Find Lexicographically smallest String with Prefix Reversal
Given a string str of length N. You have to choose a non-zero integer K (K &lt;= N), such that in one operation you can take the prefix of the string of length K and append the reverse of it to itself, the task is to find the lexicographically smallest string you can get. Examples: Input: str = "bvdfndkn"Output: bbExplanation: If we choose K = 1, t
5 min read
Count Edge reversal in a Directed Graph
Given a directed graph with n nodes from 0 to n-1, a 2d array edges[][] where edges[i] = [ui, vi] represents a directed edge going from node ui to node vi . The graph would form a tree if its edges were bi-directional, the task is to find the minimum edge direction reversals required for each node such that there is a directed path from that node t
15 min read
Minimum cost to sort strings using reversal operations of different costs
Given an array of strings and costs of reversing all strings, we need to sort the array. We cannot move strings in array, only string reversal is allowed. We need to reverse some of the strings in such a way that all strings make a lexicographic order and cost is also minimized. If it is not possible to sort strings in any way, output not possible.
15+ min read
Python3 Program to Modify given array to a non-decreasing array by rotation
Given an array arr[] of size N (consisting of duplicates), the task is to check if the given array can be converted to a non-decreasing array by rotating it. If it's not possible to do so, then print "No". Otherwise, print "Yes". Examples: Input: arr[] = {3, 4, 5, 1, 2}Output: YesExplanation: After 2 right rotations, the array arr[] modifies to {1,
3 min read
Find determinant of matrix generated by array rotation
Given an array of three elements. The task is to construct a matrix of order 3×3 by using all three rotations of the array as a row of the matrix and find the determinant of the resultant matrix. Examples: Input : arr[] = {1, 2, 3} Output : 18 Input : arr[] = {1, 1, 1} Output : 0 Approach: As per the problem statement, construct a 3*3 matrix using
4 min read
Count of elements in array A left after performing deletion/rotation operation based on given conditions
Given two binary arrays, A[] and B[] of size N respectively, the task is to find the number of elements in array A[] that will be left after performing the following operation until no elements can be deleted: If the starting elements of array A[] and B[] are equal, then delete both the elements.Otherwise, append the starting character of array A[]
9 min read
Rearrange array elements into alternate even-odd sequence by anticlockwise rotation of digits
Given an array arr[] consisting of N positive integers, the task is to rotate the digits of array elements in an anti-clockwise direction such that elements of the array elements are in alternate even-odd or odd-even form. If multiple solutions exists, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = { 143, 251, 534, 232, 8
12 min read
Python3 Program to Rearrange array elements into alternate even-odd sequence by anticlockwise rotation of digits
Given an array arr[] consisting of N positive integers, the task is to rotate the digits of array elements in an anti-clockwise direction such that elements of the array elements are in alternate even-odd or odd-even form. If multiple solutions exists, then print any one of them. Otherwise, print -1. Examples: Input: arr[] = { 143, 251, 534, 232, 8
4 min read
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 = 1k2 = 3k3 = 4k4 = 6Output : 3 5 7 9 17 9 1 3 59 1 3 5 73 5 7 9 1Input : arr[] = {1, 3, 5, 7, 9}k1 = 14 Output : 9 1 3 5 7Recommended: Please solve it on “PRACTICE ”
15+ min read
Find the Rotation Count in Rotated Sorted array
Given an array arr[] of size N having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k. Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Output: 2Explanation: Initial array must
15+ min read
Program for array left rotation by d positions.
Given an array of integers arr[] of size N and an integer d, the task is to rotate the array elements to the left by d positions. Examples:   Input: N = 7, d = 2 ,arr[] = {1, 2, 3, 4, 5, 6, 7}Output: 3 4 5 6 7 1 2 Input: N = 7, d=2 , arr[] = {3, 4, 5, 6, 7, 1, 2},Output: 5 6 7 1 2 3 4   divBlockRotate ArrayTry It!Table of Content Approach 1 (Using
15+ min read
Lexicographically minimum string rotation | Set 1
Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written Test More Examples: Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG Following is a simple solution. Let the given string be 'str' Concatenate '
5 min read
Find a rotation with maximum hamming distance
Given an array of N elements, create a new array which is a rotation of the given array, and hamming distance between both the arrays is maximum. The task is to print the maximized hamming distance between given and new arrays. Hamming distance between two arrays or strings of equal length is the number of positions at which the corresponding chara
15+ min read
Reflection of a point at 180 degree rotation of another point
Given two points coordinates (x1, y1) and (x2, y2)on 2D plane. The task is to find the reflection of (x1, y1) at 180 degree rotation of (x2, y2).Examples: Input : x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output : (2, 2) Input : x1 = 1, y1 = 1, x2 = 2, y2 = 2 Output : (3, 3) Let the reflection point of point (x1, y1) about (x2, y2) be (x', y'). For (x', y') b
4 min read
Minimum number possible such that it has X digits and it grows Y times by rotation
Given two positive integers X and Y. The task is to find the minimum possible number such that the number has X decimal digits &amp; it grows Y times after moving its last digit to first Examples: Input: X = 6, Y = 5 Output: 142857Explanation: Following are the operations performed to get the desired result.Take last digit of 142857 i.e. 7 and put
6 min read
Queries for rotation and Kth character of the given string in constant time
Given a string str, the task is to perform the following type of queries on the given string: (1, K): Left rotate the string by K characters.(2, K): Print the Kth character of the string. Examples: Input: str = "abcdefgh", q[][] = {{1, 2}, {2, 2}, {1, 4}, {2, 7}} Output: d e Query 1: str = "cdefghab" Query 2: 2nd character is d Query 3: str = "ghab
6 min read
Clockwise rotation of Linked List
Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; NULL, K = 2 Output: 4 -&gt; 5 -&gt; 1 -&gt; 2 -&gt; 3 -&gt; NULLInput: 7 -&gt; 9 -&gt; 11 -&gt; 13 -&gt; 3 -&gt; 5 -&gt; NULL, K = 12 Output: 7 -&gt; 9 -&gt; 11 -&gt; 13 -&gt;
15+ min read
Clockwise rotation of Doubly Linked List by N places
Given a doubly-linked list and an integer N, the task is to rotate the linked list clockwise by N nodes.Examples: Input: N = 2 Output: Approach: To rotate the Doubly linked list first check whether the given N is greater than the length of the list or not. If N is greater than the size of the list then deduce it in the range of linked list size by
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg