Question :
Given an array, rotate the array by one position in clock-wise direction.
Example 1:
Input:
N = 5
A[] = {1, 2, 3, 4, 5}
Output:
5 1 2 3 4
Logic:
- Traditional Approach:
- take the input as array and t as no of rotations
- rotate the loop from 0 to t
- store the last element in temp and run loop in reverse order till 1st location ( arr [ 1 ] )
- shift arr [ i ] = arr[ i - 1 ]
- put temp in arr[ 0 ]
import java.util.*;
public class Solution{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int t = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextInt();
}
for(int i = 1; i <=t ; i++){
int temp = arr[arr.length-1];
for(int j = arr.length-1; j > 0 ; j--){
arr[j] = arr[j-1];
}
arr[0] = temp;
}
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i]+" ");
}
}
}
Top comments (0)