Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate array of k position performance c#

I'm solving problems on LeetCode, and referring to this problem: 189. Rotate Array

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]

I gave my solution as:

public void Rotate(int[] nums, int k) {
    if (k <= 0)
        return;

    int t = 0;

    for (int i = 0; i < k; i++) {
        t = nums[nums.Length - 1];

        for (int j = nums.Length - 1; j > 0; j--) {
            nums[j] = nums[j - 1];
        }

        nums[0] = t;
    }
}

My question is not about the solution, but is about its performance.

Can I improve my solution to be faster? Or is wrong my approach?

Cause it pass all the test cases, but it fail the last one cause is a big array with big numbers, and it fail on being fast enough, it gives me

"Time Limit Exceeded"

like image 996
Matteo Avatar asked Sep 06 '25 21:09

Matteo


1 Answers

You could run it in a single while loop. I don't have leetcode so I can't test it, I just ran it locally but if you run this what do you get? Also, it doesn't do the in place movement so if there is a memory test it might fail that.

  public static int[] Rotate(int[] nums, int k) {
        if (k <= 0) return nums;
        var n = new int[nums.Length];
        var stopAt = nums.Length - k;
        while(stopAt < 0) {
            stopAt = nums.Length - Math.Abs(stopAt);
        }
        var i = stopAt;
        var y = 0;
        while (true) {
            n[y] = nums[i];
            y++;
            i++;
            if (i >= nums.Length) {
                i = 0;
            }
            if (i == stopAt) break;
        }
        return n;
    }
like image 173
Stephen Gilboy Avatar answered Sep 09 '25 09:09

Stephen Gilboy