
Problem Statement
The task is to rotate an array to the right by a predefined number of steps. Specifically, given an integer array nums
, the array should be rotated k
times to the right, where k
is a non-negative integer. Rotating an array means that each element is shifted rightward by one position, and the last element of the array moves to the first position, becoming the new first element.
Examples
Example 1
Input:
nums = [1,2,3,4,5,6,7], k = 3
Output:
[5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2
Input:
nums = [-1,-100,3,99], k = 2
Output:
[3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
Constraints
1 <= nums.length <= 10^5
-2^31 <= nums[i] <= 2^31 - 1
0 <= k <= 10^5
Approach and Intuition
To rotate the array efficiently, avoid performing one-step rotations repeatedly. Instead, use the following optimized steps:
Normalize
k
: Since rotating byk
wherek >= nums.length
would just loop over the array, usek = k % nums.length
.Reverse Technique (In-place): Rotate the array using three reverse operations:
- Reverse the entire array.
- Reverse the first
k
elements. - Reverse the remaining
n - k
elements.
This method ensures linear time complexity O(n)
and constant space complexity O(1)
.
Step-by-step for Example 1 (nums = [1,2,3,4,5,6,7]
, k = 3
):
- Original:
[1,2,3,4,5,6,7]
- After reversing all:
[7,6,5,4,3,2,1]
- Reverse first
k=3
:[5,6,7,4,3,2,1]
- Reverse rest:
[5,6,7,1,2,3,4]
→ Final rotated array
This approach is both optimal and scalable for large arrays.
Solutions
- C++
- Java
- Python
class Solution {
public:
void shiftRight(vector<int>& elements, int offset) {
offset %= elements.size();
invert(elements, 0, elements.size() - 1);
invert(elements, 0, offset - 1);
invert(elements, offset, elements.size() - 1);
}
void invert(vector<int>& elements, int left, int right) {
while (left < right) {
int swap = elements[left];
elements[left] = elements[right];
elements[right] = swap;
left++;
right--;
}
}
};
The provided C++ solution addresses the problem of rotating an array by performing a right rotation through a series of inversions. The code achieves the rotation without extra space for another array.
- The
shiftRight
function first adjusts the rotation offset to ensure it does not exceed the array size. - It then inverts the entire array to prepare for rotation.
- The function breaks the rotation into two parts: first, it inverts the elements from the beginning of the array to one less than the offset, effectively placing a portion of the array's end to the beginning.
- Next, it inverts the remaining elements, positioning them correctly to achieve the desired rotation.
The invert
helper function swaps elements in place to reverse the specified segment of the array. This efficient handling of array elements allows for minimal computational overhead and avoids additional memory usage normally associated with array rotation tasks. Ensure to include the vector
library when implementing this solution in your projects.
class Solution {
public void rotateArray(int[] elements, int steps) {
steps %= elements.length;
flip(elements, 0, elements.length - 1);
flip(elements, 0, steps - 1);
flip(elements, steps, elements.length - 1);
}
public void flip(int[] elements, int begin, int finish) {
while (begin < finish) {
int swap = elements[begin];
elements[begin] = elements[finish];
elements[finish] = swap;
begin++;
finish--;
}
}
}
The provided Java solution addresses the problem of rotating an array by a certain number of steps. The approach employs a helper method called flip
to reverse segments of the array for effective rotation. This method assists in achieving the desired array rotation without the need for additional space, which is a common constraint in array manipulation problems.
Understanding the
rotateArray
Method:- The rotation step count is normalized with the array's length using modulo operation to handle cases where the steps exceed the array size.
- The entire array is reversed first.
- Then, the beginning segment of the array, up to the number of steps, is reversed.
- Finally, the remainder of the array after the initial segment is reversed.
Role of the
flip
Method:- It takes three parameters: the array and two indices that mark the beginning and end of the portion to be reversed.
- This method works by swapping elements from the start and end of the specified segment until it meets in the middle, effectively reversing the segment.
This code effectively utilizes reversals to achieve the rotation, making it a space-efficient solution that operates in linear time, which is often optimal for array manipulation tasks. Ensure the steps
value is non-negative to avoid unexpected behavior, and validate input array length to handle edge cases such as an empty array or where no rotation is needed.
class Solution:
def reverseSegment(self, array: list, left: int, right: int) -> None:
while left < right:
array[left], array[right] = array[right], array[left]
left += 1
right -= 1
def rotateArray(self, array: List[int], shift: int) -> None:
length = len(array)
shift %= length
self.reverseSegment(array, 0, length - 1)
self.reverseSegment(array, 0, shift - 1)
self.reverseSegment(array, shift, length - 1)
The given Python program rotates an array to the right by a specified number of steps. This solution involves reversing specified segments of the array to achieve the rotation. Here's a breakdown of the method:
- The
reverseSegment
function reverses a portion of the array between two indices. - The main function,
rotateArray
, adjusts the shift so it's within the bounds of the array's length. - The entire array is first reversed.
- The segment from the beginning of the array to just before the shift's index is then reversed.
- Finally, the segment from the shifted index to the end of the array is reversed.
By the end of these operations, the array elements are effectively rotated to the right by the specified number of positions. This approach leverages the characteristic that reversing the whole array and then relevant sub-segments yields the same result as rotating it.
No comments yet.