Skip to content

Instantly share code, notes, and snippets.

@HDegano
Last active August 29, 2015 14:23
Show Gist options
  • Save HDegano/0df77976df978b22b93c to your computer and use it in GitHub Desktop.
Save HDegano/0df77976df978b22b93c to your computer and use it in GitHub Desktop.
Rotate Array with O(n) complexity and O(1) space
public class RotateArray {
public void rotate(int[] nums, int k) {
if(k > nums.length) k = k % nums.length;
reverse(nums, 0, nums.length);
reverse(nums, 0, k);
reverse(nums, k, nums.length);
}
private void reverse(int[] ar, int from, int upTo){
if(upTo <= from) return;
int l = upTo - from;
int mid = (from + l /2);
for(int i = from, j = upTo - 1; i < mid && j >= mid ; i++, j--){
int temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment