Rotate Array

Problem

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].

Solution

Reverse Three Times: O(n) time, O(1) space

public class Solution {
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        k %= len; //avoid duplicated rotations 
        reverse(nums, 0, len - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, len - 1);
    }

    //Helper method to reverse array 
    private void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start++] = nums[end];
            nums[end--] = temp;
        }
    }
}

Analysis

This is a very smart solution using reverse()
Take array [1, 2, 3, 4, 5, 6, 7] and k = 3 as an example
We first reverse the entire array and it becomes [7,6,5,4,3,2,1]
Then we reverse the left part of k and it becomes [5,6,7,4,3,2,1]
At the end, we reverse the right part of k so it becomes [5,6,7,1,2,3,4] ;)

results matching ""

    No results matching ""