Given an integer array
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]
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 <= 105 -231 <= nums[i] <= 231 - 1 0 <= k <= 105
- Try to come up with as many solutions as you can. There are at least three different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
Contents
Solution 1 - Using a temporary array Solution 2 - Reverse input array and rearrange elements
In this approach, we will use a temporary array and copy last
Implementation steps:
-
First, we will create a temporary array
temp with same size as input arraynums , also create a variableindex and initialize with 0, we will be using it as index pointer for this temporary array. -
Then, run a
for loop fromn-k th index to end ofnums array (lastk elements) and copy these intotemp array using theindex created above, by the end of this loopindex will be at a place where the next element can be filled from. For example if we fill 3 elements into the temporary array, thenindex will be incremented to 3. -
Next, run another
for loop from 0th index ton-k-1 th index ( remaining elements innums array from the beginning) and copy these intotemp using theindex created above. -
By this step, elements in
temp array are already rotated byk steps. So, finally, run anotherfor loop to copytemp array intonums input array.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n) for the temporary array.
In this approach, we will first reverse the input array
Example:
-
Let's consider input array as
[1, 2, 3, 4, 5, 6, 7] andk = 3 , after rotating array with 3 steps , resultant array will be[5, 6, 7, 1, 2, 3, 4] . -
First, let's reverse the array, so the array will become
[7, 6, 5, 4, 3, 2, 1] . -
Then, reverse first k elements, then the array becomes
[ .5, 6, 7 , 4, 3, 2, 1] -
Now, reverse remaining elements on right side, then the resultant array becomes
[5, 6, 7, 1, 2, 3, 4] and this is the final result that we want. - Advantage with this approach is that all operations are done in-place, so it does not require additional space.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1).
Above implementations source code can be found at