Rotate Array
Array, Two Pointers
Given an integer array nums
, rotate the array to the right by k
steps, where k
is non-negative.
Example 1:
Example 2:
Solutions
The problem is asking to rotate an array to the right by k
steps. This means that each element in the array should be moved k
positions to the right, and the elements that go beyond the end of the array should be moved to the start of the array.
Approach – Brute Force Technique
In the brute force approach, we rotate the array k
times. In each rotation, we move each element to its next position and move the last element to the start of the array.
Steps
Define the function: The function
Rotate
is defined with two parameters,nums
(an array of integers) andk
(the number of steps to rotate).Outer loop: The outer loop runs
k
times. Each iteration of this loop corresponds to a single step of rotation.Store the last element: Before shifting the elements, the last element of the array is stored in the variable
temp
. This is because it will be overwritten during the shifting process and we need to place it at the start of the array.Shift elements to the right: The inner loop runs from the end of the array to the start, shifting each element one position to the right. This is done by setting
nums[j]
tonums[j - 1]
.Place the last element at the start: After all elements have been shifted, there is an empty spot at the start of the array (i.e.,
nums[0]
). The last element that we stored intemp
is placed here.Repeat: The process is repeated
k
times to achieve the required rotation.
Complexity
Time Complexity: O(n*k)
Auxiliary Space: O(1)
Approach – Two Pointers Technique
In the optimized approach, we use the reverse operation to achieve the rotation. We first reverse the entire array, then reverse the first k
elements, and finally reverse the remaining n - k
elements.
Steps
Calculate the effective number of rotations: The number of rotations
k
is taken modulo the length of the arrayn
. This is because rotating the arrayn
times doesn't change the array, so we only need to consider the remainder ofk
divided byn
.Reverse the entire array: The
Reverse
function is called with parameters0
andn - 1
, which reverses the entire array.Reverse the first part of the array: The
Reverse
function is called again with parameters0
andk - 1
, which reverses the firstk
elements of the array.Reverse the second part of the array: The
Reverse
function is called one more time with parametersk
andn - 1
, which reverses the remainingn - k
elements of the array.
The Reverse
function is a helper function that reverses the elements in the nums
array between the start
and end
indices. It does this by swapping the elements at the start
and end
indices, and then incrementing start
and decrementing end
until start
is no longer less than end
.
Complexity
Time Complexity: O(n)
Auxiliary Space: O(1)
Last updated