Instagram
youtube
Facebook
Twitter

Left Rotation| Array

TASK(easy)

left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result.

Example

d=2

arr=[1,2,3,4,5]

After 2 rotations,

arr=[3,4,5,1,2] .

Function Description

Complete the rotateLeft function in the editor below.

rotateLeft has the following parameters:

  • int d: the amount to rotate by
  • int arr[n]: the array to rotate

Returns

  • int[n]: the rotated array

Input Format

The first line contains two space-separated integers that denote n, the number of integers, and d, the number of left rotations to perform.
The second line contains n space-separated integers that describe arr[].

Constraints

1<=n<=105
1<=d<=n
1<=a[i]<=106

Sample Input

5 4

1 2 3 4 5

Sample Output

5 1 2 3 4

SOLUTION 1

def leftRotation(a, d):

    n = len(a)

    d = d % n # Handle cases where d > n

    rotated_array = a[d:] + a[:d]

    return rotated_array



# Reading input

if __name__ == "__main__":

    # Input processing

    n, d = map(int, input().split())

    a = list(map(int, input().split()))

    result = leftRotation(a, d)

    # Print the result as a space-separated string

    print(' '.join(map(str, result)))

SOLUTION 2

def leftRotation(a, d):

     n,b=map(int,input().split())

     a=list(map(int,input().split()))[:n]

for i in range(b):

   for j in range(n-1):

    temp=a[j]

    a[j]=a[j+1]

    a[j+1]=temp

for i in range(n):

    print(a[i],end=' ') 

EXPLANATION STEPS

1. Function leftRotation(a, d):

  • Computes the rotated array by slicing. The array is split into two parts: from ‘d’ to the end and from the start to ‘d’. Concatenating these two parts gives the rotated array.

2. Handling Input and Output:

  • n, d = map(int, input().split()): Reads the size of the array and the number of rotations.
  • a = list(map(int, input().split())): Reads the array elements.
  • result = leftRotation(a, d): Gets the rotated array.
  • print(' '.join(map(str, result))): Prints the result as space-separated integers.