Naive Approach
In this i'm just using an extra array to store
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
let res = [];
let n = nums.length;
/*for case [1,2] sorting 3 times is equivalent to sorting 1 times*/
k = k % n; //to handle cases where k>n
for(let i = n-k ;i<n;i++){
res.push(nums[i])
}
for(let i = 0 ;i<n-k;i++){
res.push(nums[i])
}
for (let i = 0; i < n; i++) {
nums[i] = res[i];
}
};
Approach With O(1) space complexity
Javascript Code
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
k = k%nums.length
const reverseArray = (l,r) =>{
while(l<r){
[nums[l] ,nums[r]] = [nums[r] ,nums[l]]
l++;
r--;
}
}
// Reverse the entire array
reverseArray(0, nums.length - 1);
// Reverse the first k elements
reverseArray(0, k - 1);
// Reverse the remaining elements
reverseArray(k, nums.length - 1);
};
If you still don't understand please go through the video by Neetcode
Top comments (0)