Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created October 26, 2024 17:53
Show Gist options
  • Save sAVItar02/491ed3cd691ea807278374b8ae27e04c to your computer and use it in GitHub Desktop.
Save sAVItar02/491ed3cd691ea807278374b8ae27e04c to your computer and use it in GitHub Desktop.
Rotate Array By K
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
if(k > nums.length) k = k % nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
};
function reverse(arr, left, right) {
while(left < right) {
let temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
}
// Reverse the entire array first [1, 2, 3, 4, 5, 6, 7] --> [7, 6, 5, 4, 3, 2, 1]
// Reverse only the amount needed to rotate [7, 6, 5, 4, 3, 2, 1] --> [5, 6, 7, 4, 3, 2, 1]
// Reverse the rest of the array [5, 6, 7, 4, 3, 2, 1] --> [5, 6, 7, 1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment