Problem: Arrays Left Rotation

  • Difficulty: Easy

Problem description:
Array Left Rotation pdf

All approaching ideas is inspired by Python.
Approach: The first thing come in my mind is using a for loop, using Python list slice notation. But it’s too expensive both in computing muscle and memory usage. With the constraints, it will get TLE. Another approach is using modular arithmetic. Basically, rotate array d times means that we start iterating at index d. We have to use modular arithmetic to wrap around the array in case of reaching the end of array but still haven’t iterated through all elements yet.

Implementation: Python 3

def rotate(arr, d):
    count = 0
    start = d % len(arr)
    while count < len(arr):
        print(arr[start], end=' ')
        count += 1
        start = (start + 1) % len(arr)

if __name__ == '__main__':
    n, d = list(map(int, input().strip().split()))
    arr = list(map(int, input().strip().split()))
    rotate(arr, d)