data-structures · intermediate · ~15 min

Rotate array right by k

Index arithmetic with modular shifts.

Challenge

Rotate the elements of an array to the right by k positions.

Task

Implement void rotate_right(int *a, size_t n, size_t k) that rotates the n elements of a to the right by k positions, in place. Each element moves k slots toward the end, and elements pushed off the end wrap to the front. k may be larger than n.

Input

  • a: writable array of n ints.
  • n: the number of elements.
  • k: the rotation amount (may exceed n; the effective shift is k % n).

Output

Nothing returned; a is rotated in place.

Example

{1,2,3,4,5}, k=2   ->   {4,5,1,2,3}
{1,2,3}, k=5       ->   {2,3,1}    (effective k = 5 % 3 = 2)

Edge cases

  • n == 0 or an effective shift of 0 leaves the array unchanged.
  • k larger than n wraps via k % n.

Input format

a: writable array of n ints; n; k (may exceed n).

Output format

Nothing returned; a is rotated right by k in place.

Constraints

Effective shift is k % n; handle k >= n.

Starter code

#include <stddef.h>
void rotate_right(int *a, size_t n, size_t k) { /* TODO */ }

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.