Skip to content

Instantly share code, notes, and snippets.

@ShlomiRex
Last active February 22, 2017 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShlomiRex/824895ce407df155378133bc1b56f621 to your computer and use it in GitHub Desktop.
Save ShlomiRex/824895ce407df155378133bc1b56f621 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
//initializing regular code...
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int d = s.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++)
arr[i] = s.nextInt();
//for optimal solution, if n==d or d is multiple of n then we do nothing.
//example: move array of 5 elements, 5 place to the left. We do nothing.
//Therefor we remove from d the multiple of n.
//if d is not multiple of n
if(d%n != 0) {
if(d > n) {
while(d>n) {
//here we remove n from d. (But we need to check when to stop.)
if(d < n)
break;
d -= n;
}
}
/*
after all the work we got d that is 100% less than n. which is good, so we don't need to do mutliple
rotations to get to the same result.
My optimal solution:
Create new list of size n. Add all elements from arr[] to new list, starting from index d (included)
up to index arr.length (which is n) . That way only the "rotating elements from left to right" will
be added later, and the "not rotating elements from left to right" are added immidietly, without checking.
*/
int[] newArr = new int[n];
for(int i = 0; i < (n - d); i++)
newArr[i] = arr[d+i];
//we done adding all "non rotating elements"
//now append all "moving elements"
//they are in arr[] from index (include) 0 to index (include) d-1 .
for(int i = 0; i < d; i++)
newArr[n-d+i] = arr[i];
//and we done!
//print result
for(int i = 0; i < n; i++)
System.out.print(newArr[i] + " ");
}
else
//print result
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment