Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to solve a Hackerrank problem where you perform k array[n] rotations, and at the end, ask for m and print array[m]. My program is probably correct (it runs perfectly for most of tests, but some of them terminate due to timeout), but is inefficient and I don't know how to improve it.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int n; 
    int k; 
    int q; 
    scanf("%d %d %d",&n,&k,&q);
    int *a = malloc(sizeof(int) * n);
    int *b = malloc(sizeof(int) * n);
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&a[a_i]);
    }
    for(int i = 0; i < k; i++){
        b[0] = a[n-1];
        for(int a_i = 1; a_i < n; a_i++){
        b[a_i] = a[a_i-1];
        }
        for(int a_i = 0; a_i < n; a_i++) a[a_i] = b[a_i];
    }
    for(int a0 = 0; a0 < q; a0++){
    int m; 
    scanf("%d",&m);
    printf("%d\n", b[m]);
    }
    return 0;
}
share|improve this question
up vote 10 down vote accepted

Do not do actual rotation.

k rotations (from your code I understand that all rotations are to the right by 1) map an i'th element to an (i + k) % n position. At the time of printing, do some math to figure out which element was mapped to the position m.

The math is trivial, and I intentionally do not spell it out.

share|improve this answer
    
Exactly that. Don' move the data. Adjust the indexes to the data. – Tonny yesterday
1  
If the data really must be moved, it could be done in one step instead of k steps though, and even in-place (by using xor). – mirabilos yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.