Skip to content

Commit 32b6e46

Browse files
committed
Update rotate array logic
1 parent 6dcf770 commit 32b6e46

File tree

2 files changed

+68
-30
lines changed

2 files changed

+68
-30
lines changed
Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,55 @@
1-
// 1. Reversal approach using two pointers
1+
// 1. Rotate Array Using Reversal Algorithm (Efficient O(n) time, O(1) space)
22
function rotate(nums, n) {
33
const length = nums.length;
4-
n %= length;
4+
if (length === 0 || n % length === 0) return nums; // No rotation needed
55

6-
reversal(nums, 0, length-1);
7-
reversal(nums, 0, n-1);
8-
reversal(nums, n, length-1);
6+
n = n % length; // Handle n > length
7+
8+
// Reverse entire array
9+
reverse(nums, 0, length - 1);
10+
// Reverse first part
11+
reverse(nums, 0, n - 1);
12+
// Reverse second part
13+
reverse(nums, n, length - 1);
914

1015
return nums;
1116
}
1217

13-
function reversal(nums, start, end) {
14-
while(start < end) {
15-
[nums[start], nums[end]] = [nums[end], nums[start]];
18+
// Helper function to reverse elements between two indices
19+
function reverse(arr, start, end) {
20+
while (start < end) {
21+
[arr[start], arr[end]] = [arr[end], arr[start]];
1622
start++;
1723
end--;
1824
}
1925
}
2026

21-
// 2. BrutForce using unshift() and pop() methods
27+
// 2. Rotate Array Using Brute Force with pop() and unshift() (Inefficient: O(n^2) time)
28+
function rotateBruteForce(nums, n) {
29+
const length = nums.length;
30+
if (length === 0) return;
2231

23-
function rotateBrutforce(nums, n) {
24-
for(let i=0; i< n; i++) {
32+
n = n % length;
33+
for (let i = 0; i < n; i++) {
2534
nums.unshift(nums.pop());
2635
}
2736
}
2837

38+
// ----------------------------
39+
// Test Cases
40+
// ----------------------------
2941
let rotate1 = [1, 2, 3, 4, 5, 6, 7];
30-
console.log("Before rotate:", rotate1);
42+
console.log("Before rotate (reversal):", [...rotate1]);
3143
rotate(rotate1, 4);
32-
console.log("After rotate:", rotate1);
44+
console.log("After rotate (reversal):", rotate1);
3345

3446
let rotate2 = [-10, 4, 5, -1];
35-
console.log("Before rotate:", rotate2);
36-
rotateBrutforce(rotate2, 2);
37-
console.log("After rotate:", rotate2.join);
47+
console.log("Before rotate (brute force):", [...rotate2]);
48+
rotateBruteForce(rotate2, 2);
49+
console.log("After rotate (brute force):", rotate2);
50+
51+
// Edge case
52+
let rotate3 = [1];
53+
console.log("Before rotate (single element):", [...rotate3]);
54+
rotate(rotate3, 10);
55+
console.log("After rotate (single element):", rotate3);
Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,57 @@
11
**Description**
2-
Given an integer array `nums`, rotate the array to the right by `n` steps, where `n` is non-negative number.
2+
Given an integer array `nums`, rotate the array to the right by `n` steps, where `n` is a non-negative number. The rotation is performed **in-place**, meaning no additional array is used for the operation.
33

44
### Examples
55
Example 1:
66

77
Input: nums = [1,2,3,4,5,6,7], n = 4
8-
Output: [5,6,7,1,2,3,4]
8+
Output: [4,5,6,7,1,2,3]
99

1010
Example 2:
1111

1212
Input: nums = [-10, 4, 5, -1], n = 2
1313
Output: [5, -1, -10, 4]
1414

15-
**Algorithmic Steps:**
16-
This problem is solved with the help of **two pointers** technique, which is used to reverse subarrays. The algorithmic approach can be summarized as follows:
15+
**Algorithm overview:**
16+
This algorithm leverages the **reversal technique** (a two-pointer approach) to efficiently rotate the array in-place.
1717

18-
1. Initialize `length` variable to store length of an input array.
18+
To rotate the array to the right by `n` steps:
1919

20-
2. Update the number of times rotation(i.e, `n`) to `n % length` incase of number of rotations greater than length of an array.
20+
1. Reverse the entire array.
21+
2. Reverse the first `n` elements.
22+
3. Reverse the remaining `length - n` elements.
2123

22-
3. Create a helper function to reverse elements of an array using swap operation with the help left and right pointers(i.e, `left` and `right`). The left pointer needs to be incremented and right pointer needs to decremented for each iteration.
24+
#### Detailed steps:
2325

24-
4. Invoke reversal operation for entire array of elements(i.e, from the beginning to end of an array).
26+
1. **Calculate Array Length**
27+
Initialize a variable `length` to store the total number of elements in the array.
2528

26-
5. Invoke reversal operation for first `n` number of elements(i.e, from the beginning to n-1).
29+
2. **Edge case**
30+
No rotation is required when the given array is empty and number of rotations is equals to the length of an array. This condition is helpful for early exit.
31+
32+
3. **Normalize the Rotation Count**
33+
Update the rotation count by taking `n % length` to handle cases where `n` exceeds the array size. This ensures we perform only the necessary rotations.
2734

28-
6. Invoke reversal operation for remaining number of elements(i.e, from `n-1` to end of an array).
35+
4. **Define a Reversal Helper Function**
36+
Implement a helper function that reverses elements between two indices (`left` and `right`) in the array using a two-pointer technique. Swap the elements at `left` and `right`, then increment `left` and decrement `right` in each iteration until both pointers meet.
2937

30-
7. Return in-place rotated array as output.
38+
5. **Reverse the Entire Array**
39+
Apply the reversal function to the full array (from index `0` to `length - 1`). This step brings the elements that need to be rotated to the front, but in reverse order.
3140

32-
**Time and Space complexity:**
41+
6. **Reverse the First `n` Elements**
42+
Reverse the first `n` elements (from index `0` to `n - 1`) to restore them to the correct order.
3343

34-
This algorithm has a time complexity of `O(n)`, where `n` is the number of elements. This is because we are performing three reversal operations on subarrays and each reversal operation takes `O(n)`. So the overall time complexity is `O(n)`.
44+
7. **Reverse the Remaining Elements**
45+
Reverse the remaining elements (from index `n` to `length - 1`) to place the original beginning of the array back in the correct order.
3546

36-
Here, we don't use any additional datastructure due to in-place rotation. Hence, the space complexity will be `O(1)`.
47+
8. **Return the Rotated Array**
48+
The array has now been successfully rotated in-place and is ready for use.
49+
50+
## Time and Space Complexity
51+
52+
- **Time Complexity:** `O(n)`
53+
The algorithm performs three reverse operations, each taking `O(n)` time in total.
54+
55+
- **Space Complexity:** `O(1)`
56+
The rotation is done in-place, using only a constant amount of extra space regardless of input size.
3757

0 commit comments

Comments
 (0)