- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rotate Array in Python
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
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]
Advertisements