</>EmbeddedInterview
← All problems · Arrays & Searching

Rotate a Sample Buffer Left

Medium

Rotate n samples left by k positions in place, accepting k greater than n. Implement void rotate(int *a, size_t n, size_t k).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Reverse each segment, then the entire array.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
static void rev(int *a,size_t n){for(size_t i=0;i<n/2;++i){int t=a[i];a[i]=a[n-1-i];a[n-1-i]=t;}}
void rotate(int *a, size_t n, size_t k)
{
    if(!n)return; k%=n; rev(a,k); rev(a+k,n-k); rev(a,n);
}

Three reversals achieve O(n) time and O(1) space.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    int a[]={1,2,3,4,5};
    CHECK((rotate(a,5,2),a[0]==3 && a[4]==2 && a[3]==1));
    CHECK((rotate(a,5,8),a[0]==1 && a[4]==5));
    CHECK((rotate(NULL,0,9),1));
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}