Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time Limit Exceeded on Hackerrank

I successfully solved a question on Hackerrank, and it passed all test cases but I got an error Time Limit Exceeded. I'm guessing if I optimize my code it would work,but I can't think of any way to make my code more efficient.

The question is: A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].

Given an array of n integers and a number, d, perform d left rotations on the array. Then print the updated array as a single line of space-separated integers.

Can any one please guide me on how to make this code more efficient?

My code is:

vector<int> array_left_rotation(vector<int> a, int n, int k) {
    for (int j = 0; j < k; j++){
        a[n] = a[0];
        for (int i = 0; i < n; i++){
            a[i] = a[i+1];
        }
        a[n-1] = a[n];
    }
    return a;
}

n is the number of elements in the array k is the number of rotations to be performed

like image 561
Hassaan Hasan Avatar asked Oct 31 '25 02:10

Hassaan Hasan


2 Answers

You don't need to actually rotate the array for this problem. The formula (i + k) % n will give you the element at index i in an array that has been rotated k times to the left. Knowing this you can pass through the array once accessing each element in this manner:

int main() {
  int* arr, n, k, i;
  cin >> n >> k;
  arr = new int[n];
  for (i = 0; i < n; ++i)
    cin >> arr[i];
  for (i = 0; i < n; ++i)
    cout << arr[(i + k) % n] << " ";
}
like image 158
David G Avatar answered Nov 01 '25 17:11

David G


Instead of performing k rotations, try performing a k-rotation: Rotate the entire array left by k in one go. That's much more efficient.

like image 34
matanso Avatar answered Nov 01 '25 17:11

matanso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!