HackerRank ‘Left Rotation’ Solution

H
Short Problem Definition:

left rotation operation on an array shifts each of the array’s elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].

Link

Arrays: Left Rotation

Complexity:

time complexity is O(N)

space complexity is O(N)

Execution:

Solutions like this is where python really shines. Simple and straight forward.

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/python
 
import math
import os
import random
import re
import sys
 
# Complete the rotLeft function below.
def rotLeft(a, d):
    return a[d:] + a[:d]
 
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')
 
    nd = raw_input().split()
 
    n = int(nd[0])
 
    d = int(nd[1])
 
    a = map(int, raw_input().rstrip().split())
 
    result = rotLeft(a, d)
 
    fptr.write(' '.join(map(str, result)))
    fptr.write('n')
 
    fptr.close()

About the author

Add comment

Archives

Categories