Simvik

Rotate an array

Rotate a buffer left by k positions in place. A medium embedded C problem (Arrays and strings), run and graded in the browser.

medium · Arrays and strings · arrays · in-place

Rotate the n bytes at buf left by k positions, in place: the element at index k moves to index 0, and the first k elements wrap around to the end.

k may be larger than n. Use only a constant amount of extra memory.

Starter code

void rotate_left(uint8_t *buf, size_t n, size_t k) {
  // {1,2,3,4,5} rotated left by 2 is {3,4,5,1,2}.
}

Example tests

Rotate by two

uint8_t b[] = { 1, 2, 3, 4, 5 };
rotate_left(b, 5, 2);
printf("%u %u %u %u %u\n", b[0], b[1], b[2], b[3], b[4]);

Expected output:

3 4 5 1 2

Rotate by zero

uint8_t b[] = { 1, 2, 3, 4, 5 };
rotate_left(b, 5, 0);
printf("%u %u %u %u %u\n", b[0], b[1], b[2], b[3], b[4]);

Expected output:

1 2 3 4 5

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems