array rotation c++ code example
Example 1: Rotation of array in C++
Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7
1) Store the first d elements in a temp array
temp[] = [1, 2]
2) Shift rest of the arr[]
arr[] = [3, 4, 5, 6, 7, 6, 7]
3) Store back the d elements
arr[] = [3, 4, 5, 6, 7, 1, 2]
Example 2: rorate array
function rotateArray(A, K) {
if (!A.length) return A;
let index = -1;
while (++index < K) {
A.unshift(A.pop());
}
return A;
}
[
rotateArray([3, 8, 9, 7, 6], 3),
rotateArray([0, 0, 0], 1),
rotateArray([1, 2, 3, 4], 4),
rotateArray([], 4),
].join(' | ');