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
- 1 ≤ nums.length ≤ 10⁵
- -2³¹ ≤ nums[i] ≤ 2³¹ − 1
- 0 ≤ k ≤ 10⁵
- Follow-up: O(1) extra space
Edge cases to test
- k larger than n: use
k % n - k = 0 or k = n
- One element
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 - 1C++
#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
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Next Permutation (Medium)
- 3Sum (Medium)