Thursday, May 11, 2017

Rotate Array


Problem Statement

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]
Link to GitHub: Code



Solution

  • Reverse the array
  • Change the values in the array k-1 position
  • Change the values in the array from k position

public class RotateArray {
 public static int [] getOptimum(int[] arr, int k)
 {
     
     k%=arr.length; //k=k%arr.length
     //Reverse the array
     reverse(arr,0,arr.length-1);
     //Change the values in the array k-1 position
     reverse(arr,0,k-1);
     //Change the values in the array from k position
     reverse(arr,k,arr.length-1);
  
  return arr;
 }
 public static void reverse(int [] arr, int start,int end){
  while(start<end)
  {
   int temp =arr[start];
   arr[start]=arr[end];
   arr[end]=temp;
   
   start++;
   end--;
  }
 } 

}

Output


No comments:

Post a Comment