[LeetCode]189 Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

Solution


Approach #1 Brute Force [Time Limit Exceeded]

The simplest approach is to rotate all the elements of the array in k steps by rotating the elements by 1 unit in each step.

Java

public class Solution {
    public void rotate(int[] nums, int k) {
        int temp, previous;
        for (int i = 0; i < k; i++) {
            previous = nums[nums.length - 1];
            for (int j = 0; j < nums.length; j++) {
                temp = nums[j];
                nums[j] = previous;
                previous = temp;
            }
        }
    }
}

Complexity Analysis

  • Time complexity : O(n*k)O(nk). All the numbers are shifted by one step(O(n)O(n)) k times(O(k)O(k)).
  • Space complexity : O(1)O(1). No extra space is used.

Approach #2 Using Extra Array [Accepted]

Algorithm

We use an extra array in which we place every element of the array at its correct position i.e. the number at index ii in the original array is placed at the index (i+k)(i+k). Then, we copy the new array to the original one.

Java

public class Solution {
    public void rotate(int[] nums, int k) {
        int[] a = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            a[(i + k) % nums.length] = nums[i];
        }
        for (int i = 0; i < nums.length; i++) {
            nums[i] = a[i];
        }
    }
}

Complexity Analysis

  • Time complexity : O(n)O(n). One pass is used to put the numbers in the new array. And another pass to copy the new array to the original one.

  • Space complexity : O(n)O(n). Another array of the same size is used.


Approach #3 Using Cyclic Replacements [Accepted]

Algorithm

We can directly place every number of the array at its required correct position. But if we do that, we will destroy the original element. Thus, we need to store the number being replaced in a temptemp variable. Then, we can place the replaced number(temptemp) at its correct position and so on, nn times, where nn is the length of array. We have chosen nn to be the number of replacements since we have to shift all the elements of the array(which is nn). But, there could be a problem with this method, if nn where k=kk=k(since a value of kk larger than nn eventually leads to a kk equivalent to kk). In this case, while picking up numbers to be placed at the correct position, we will eventually reach the number from which we originally started. Thus, in such a case, when we hit the original number's index again, we start the same process with the number following it.

Now let's look at the proof of how the above method works. Suppose, we have nn as the number of elements in the array and kk is the number of shifts required. Further, assume nn. Now, when we start placing the elements at their correct position, in the first cycle all the numbers with their index ii satisfying ii get placed at their required position. This happens because when we jump k steps every time, we will only hit the numbers k steps apart. We start with index i=0i=0, having ii. Thus, we hit all the numbers satisfying the above condition in the first cycle. When we reach back the original index, we have placed \frac{n}{k}knelements at their correct position, since we hit only that many elements in the first cycle. Now, we increment the index for replacing the numbers. This time, we place other \frac{n}{k}kn elements at their correct position, different from the ones placed correctly in the first cycle, because this time we hit all the numbers satisfy the condition ii. When we hit the starting number again, we increment the index and repeat the same process from i=1i=1 for all the indices satisfying ii. This happens till we reach the number with the index ii again, which occurs for i=ki=k. We will reach such a number after a total of k cycles. Now, the total count of numbers exclusive numbers placed at their correct position will be k \times \frac{n}{k}=nk×kn=n. Thus, all the numbers will be placed at their correct position.

Look at the following example to clarify the process: nums: [1, 2, 3, 4, 5, 6] k: 2

Rotate Array

java

public class Solution {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        int count = 0;
        for (int start = 0; count < nums.length; start++) {
            int current = start;
            int prev = nums[start];
            do {
                int next = (current + k) % nums.length;
                int temp = nums[next];
                nums[next] = prev;
                prev = temp;
                current = next;
                count++;
            } while (start != current);
        }
    }
}

Complexity Analysis

  • Time complexity : O(n)O(n). Only one pass is used.

  • Space complexity : O(1)O(1). Constant extra space is used.


Approach #4 Using Reverse [Accepted]

Algorithm

This approach is based on the fact that when we rotate the array k times, kk elements from the back end of the array come to the front and the rest of the elements from the front shift backwards.

In this approach, we firstly reverse all the elements of the array. Then, reversing the first k elements followed by reversing the rest n-knk elements gives us the required result.

Let n=7n=7 and k=3k=3.

Original List                   : 1 2 3 4 5 6 7
After reversing all numbers     : 7 6 5 4 3 2 1
After reversing first k numbers : 5 6 7 4 3 2 1
After revering last n-k numbers : 5 6 7 1 2 3 4 --> Result

java

public class Solution {
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}

Complexity Analysis

  • Time complexity : O(n)O(n)nn elements are reversed a total of three times.

  • Space complexity : O(1)O(1). No extra space is used.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值