
Coding Interview Question on Rotating Arrays:
- Given an array, rotate the array to the right by
k
steps, wherek
is non-negative.
Coding Solution Approach:
There are at least three different ways to solve this question. One can use the in-place 0(1) extra space to approach this question.
The first easiest method would be to use the additional memory. One can also solve the question without using any additional memory. Not using additional memory can be costly and take more time to compute. The other method is to use the reverse array method. This method will reverse the given set of array or part of it until it obtains the right or desired results.
The other method is by using the cyclic-dependencies strategy. This is a more complex way of solving the question. The method works by placing each element in the array in its original position. While doing this, it keeps track of the element originally in that position. For instance, in every step of the process, an element will be placed in its rightful position while keeping track of the element that is already there or by overwriting using an additional variable.
Using the input values below, we will solve the question using the rotate one by one method:
Input: nums = [1,2,3,4,5,6,7,8,9,0], k = 4
You have to remember that the above input reads that;
You will be required to rotate the elements in the given arrays as follows:
rotate 1 steps to the right: [0,1,2,3,4,5,6,7,8,9] rotate 2 steps to the right: [9,0,1,2,3,4,5,6,7,8] rotate 3 steps to the right: [8,9,0,1,2,3,4,5,6,7] rotate 4 steps to the right: [7,8,9,0,1,2,3,4,5,6]
Based on the above explanation, the code using Python will look like this:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k%=n
nums[:] = nums[n-k:] + nums[:n-k]
nums = [1,2,3,4,5,6,7,8,9,0]
k = 4
ob1 = Solution()
ob1.rotate(nums, k)
print(nums)
If you have any question or comments, do not hesitate to ask us.
Quote: The moon looks upon many night flowers; the night flowers see but one moon. – Jean Ingelow