Given an array of size N, rotate it by D elements.

using System;

public class Program
{
public static void Main()
{
ArrayOperations obj = new ArrayOperations();
int[] arr = new int[]{1,2,3,4,5,6,7};
obj.Rotate(arr,7);
Console.WriteLine("");
obj.Rotate(arr,0);
Console.WriteLine("");
obj.Rotate(arr,2);
}
}
//Given an array of size N, rotate it by D elements.
//D <= N
//example : 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2
//the solution has Time complexity on O(n) and space complexity on O(n)
public class ArrayOperations
{
public void Rotate(int[] arr, int RotateBy)
{
if(RotateBy <= arr.Length)
{
int[] arr2 = new int[arr.Length];
//Put a first for loop from RotateBy to end of the array
//Assign the values in the new array which start from 0
for(int i= RotateBy ; i < arr.Length ; i++)
{
arr2[i-RotateBy] = arr [i];
}
//Second loop is from 0 to until we reach RotateBy position
//Assign the values in the new array which start from arr.Length - RotateBy as the values prior to this has been assigned already in above loop
for(int i= 0 ; i < RotateBy ; i++)
{
arr2[arr.Length - RotateBy + i] = arr[i] ;
}
PrintArray(arr2) ;
}
else
{
Console.WriteLine("Can not rotate the array more than its length");
}
}

public void PrintArray(int[] arr)
{
for(int i=0 ; i< arr.Length; i++)
{
Console.Write(arr[i].ToString() + " ");
}
}
}

Leave a comment