101 Logo
onenoughtone

Code Implementation

Array Rotator Implementation

Below is the implementation of the array rotator:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Array Reversal Approach
* Time Complexity: O(n) - We need to reverse the array three times
* Space Complexity: O(1) - We only use a constant amount of extra space
*
* @param {number[]} nums - The array to be rotated
* @param {number} k - The number of steps to rotate
* @return {void} Do not return anything, modify nums in-place instead
*/
function rotate(nums, k) {
const n = nums.length;
k %= n; // Calculate effective number of rotations
if (n === 1 || k === 0) {
return; // No rotation needed
}
// Helper function to reverse a portion of the array
function reverse(start, end) {
while (start < end) {
// Swap elements at start and end indices
const temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
// Reverse the entire array
reverse(0, n - 1);
// Reverse the first k elements
reverse(0, k - 1);
// Reverse the remaining n-k elements
reverse(k, n - 1);
}

Step-by-Step Explanation

Let's break down the implementation:

  1. 1. Understand the Problem: First, understand that we need to rotate an array to the right by k steps, which means each element should be moved k positions to the right, with elements that go beyond the end of the array wrapping around to the beginning.
  2. 2. Calculate Effective Rotations: Calculate the effective number of rotations as k % n, where n is the length of the array, since rotating by n steps brings the array back to its original state.
  3. 3. Implement the Array Reversal Approach: Use the array reversal technique to perform the rotation in-place with O(1) extra space.
  4. 4. Reverse the Entire Array: First, reverse the entire array to get a partially rotated result.
  5. 5. Reverse the First k Elements: Reverse the first k elements to put them in their correct order.
  6. 6. Reverse the Remaining Elements: Reverse the remaining n-k elements to complete the rotation.
  7. 7. Handle Edge Cases: Consider edge cases such as when the array has only one element or when k is 0 or a multiple of the array length.
ProblemSolutionCode
101 Logo
onenoughtone