Rotate Array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array A. We have to rotate right it k steps. So if the array is A = [5, 7, 3, 6, 8, 1, 5, 4], and k = 3, then the output will be [1,5,4,5,7,3,6,8]. The steps are like

  • [4,5,7,3,6,8,1,5]
  • [5,4,5,7,3,6,8,1]
  • [1,5,4,5,7,3,6,8]

To solve this, we will follow these steps.

  • let n is the size of the array
  • k = k mod n
  • A = subarray of A from n – k to end + subarray of A from 0 to n – k – 1

Let us see the following implementation to get a better understanding −

Example

 Live Demo

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 = [5,7,3,6,8,1,5,4]
ob1 = Solution()
ob1.rotate(nums, 3)
print(nums)

Input

nums = [5,7,3,6,8,1,5,4]
k = 3

Output

[1,5,4,5,7,3,6,8]
raja
Published on 09-Jan-2020 11:33:24
Advertisements