Arrays: Left Rotation solution

Problem

pdf

See this link on how to link to static files in Hugo.

Solution

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the rotLeft function below.
def rotLeft(a, d):
    for i in range(d):
        a.append(a.pop(0))
    return a

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    nd = input().split()

    n = int(nd[0])

    d = int(nd[1])

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

    result = rotLeft(a, d)

    fptr.write(' '.join(map(str, result)))
    fptr.write('\n')

    fptr.close()

Main idea

  • Pop the first element and append it at the same time to the array, repeat d times

Lessons learned

  • What is the simplest solution that you can think of?
  • Can you split it up into a step that you have to repeat x times?