Rotate an Array by K Positions

Problem

Rotate an array to the left by k positions, in place.

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

Python Solution

def rotate_left(nums, k):
    n = len(nums)
    k = k % n
    nums[:] = nums[k:] + nums[:k]
    return nums

C++ Solution

void rotateLeft(vector<int>& nums, int k) {
    int n = nums.size();
    k = k % n;
    reverse(nums.begin(), nums.begin() + k);
    reverse(nums.begin() + k, nums.end());
    reverse(nums.begin(), nums.end());
}

Java Solution

class Solution {
    public void rotateLeft(int[] nums, int k) {
        int n = nums.length;
        k = k % n;
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
        reverse(nums, 0, n - 1);
    }

    private 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

Time: O(n) — the reversal approach touches every element a constant number of times. Space: O(1) for the C++/Java reversal approach; the Python slicing version uses O(n) extra space for the new list.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.