I have an array and I would like to shift the array elements by n-indexes. For simplicity of the problem, let's say, I would like to shift by 1-index
and then, I can write a while
or recursion
to make it n-times
.
Say, the array is A = [3, 8, 9, 7, 6]
and I would like to right shift
by 1-index
to make it A = [6, 3, 8, 9, 7]
I think of an HashMap that will take indexes and will shift by n-indexes. Say,
Map<Integer, Integer> map = new HashMap<>();
int n = 2;
for(int j =0; j < arr.length; j++){
if(j+2 > arr.length -1){
map.put(j+2 - arr.length, arr[j]);
}
map.put(j+2, arr[j]);
}
for(Map.Entry<Integer, Integer> map : amp.entrySet()){
arr[map.getKey()] = map.getValue();
}
The solution doesn't feel very good to me. How to write the algorithm for it ?