Featured

Rotating An Array - GeeksForGeeks Practice Problem | Basic

 In today's blog post, let's discuss on solving the GeekForGeeks problem on rotating of an array by d elements.

Problem Statement: Given an array arr[]. The task is to rotate the array by d elements where d ≤ arr.size.

Examples:

Input: arr[] = [-1, -2, -3, 4, 5, 6, 7], d = 2

Output: [-3, 4, 5, 6, 7, -1, -2]

Explanation: 

Rotate by 1: [-2, -3, 4, 5, 6, 7, -1]

Rotate by 2: [-3, 4, 5, 6, 7, -1, -2]

Input: arr[] = [1, 3, 4, 2], d = 3 

Output: [2, 1, 3, 4]

Explanation: After rotating the array three times, the first three elements shift one by one to the right.


Solving The Problem:

From the above examples, we can easily understand that we need to rotate, or in other words, move the element by 'd' number of times.

In the above explanation given to the example problem, shows that the original array is being modified.

Let's take the Input array as [-1,-2,-3,4,5,6,7]

Now what could we do to modify the array to move the first element to the last of the array ? The code should be optimized to obtain the desired results. 

The simplest way is to slice the array.

Code:

class Solution:
    def leftRotate(self, arr, d):
        
        n = len(arr)
        
        arr[:]=arr[d:n]+arr[:d]
        
        return arr
        
#Driver Code

ob=Solution()

ob.leftRotate([-1,-2,-3,4,5,6,7],2)

The above code has the following:

  • Class named 'Solution.

  • Function named 'leftRotate' with 2 parameters arr and d
Followed by the calling of the class object Solution and the function leftRotate.

When the code is run, 

  • The class Solution is called.

  • Now, we access the leftRotate function through the ob. The ob is the object that called the class Solution.

  • In Python, every variable is an object,

The leftRotate function has the following code:

        
        n = len(arr)
        
        arr[:]=arr[d:n]+arr[:d]
        
        return arr

The most important line of code is the second line.

arr[:] = arr[d:n]+arr[:d]

What's the purpose of this code?

This is the one single line that performs the entire rotating of the array. The logic of our entire code lies here,

arr[:] -Refers to the currently passed array, that need to be modified.

arr[d:n] - the array is slicing from the end of d (eg: end of index 2) till the end of the length of the string.

The output would be:-

[-3,4,5,6,7]

arr[:d] - Now this slices the initial array from the beginning till d. In our case till the index of 1. The end of the index is inclusive.

The output would be:-

[-1,-2]

Now, we are modifying the array by concatenating both arrays into one array of the original array.

Finally, we are returning the modified array.

Compilation Results:

Rotating An Array - GeeksForGeeks Practice Problem Compilation Window
Submission Results:

Rotating An Array - GeeksForGeeks Practice Problem Submission Window


Problem Link

Comments

Popular Posts