Algo-Sim › Two Pointers

Rotate Array

Medium · Two Pointers · step through it in Java, Python and C++ on your own input

Rotate right by k in place: reverse everything, then reverse the first k and the remaining n − k.

Problem

Rotate the array nums to the right by k steps, in place: every value moves k positions right, and values that fall off the end wrap around to the front. k can be larger than the length of the array.

Constraints

Edge cases to test

Follow-up questions

Is there another O(1)-space way?
Cyclic replacements: move each value k ahead along cycles; there are gcd(n, k) cycles. O(n) time, O(1) space.
What if extra memory is allowed?
Copy into a new array at index (i + k) % n: O(n) time and space, simplest to get right.

Solution

Java

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

private void reverse(int[] nums, int lo, int hi) {
    while (lo < hi) {
        int t = nums[lo]; nums[lo++] = nums[hi]; nums[hi--] = t;
    }
}

Python

def rotate(nums, k):
    n = len(nums)
    k %= n
    reverse(nums, 0, n - 1)
    reverse(nums, 0, k - 1)
    reverse(nums, k, n - 1)


def reverse(nums, lo, hi):
    while lo < hi:
        nums[lo], nums[hi] = nums[hi], nums[lo]
        lo, hi = lo + 1, hi - 1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    void rotate(vector<int> &nums, int k) {
        int n = nums.size();
        k %= n;
        reverse(nums, 0, n - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, n - 1);
    }

  private:
    void reverse(vector<int> &nums, int lo, int hi) {
        while (lo < hi) {
            swap(nums[lo++], nums[hi--]);
        }
    }
};

More Two Pointers problems