Skip to content

Commit 352d5ad

Browse files
committed
Added the array rotation question, without using temp array.
1 parent 1a1d38e commit 352d5ad

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Array Rotations:-
3+
4+
Given an array, rotate the elements of the array without using the temp array.
5+
6+
Solution:-
7+
Rotate the given array one at a time, and then call the rotation function n times,(n being the times rotated)
8+
9+
Note:- Code using the temp array is also given.
10+
"""
11+
12+
#==================== Method 1: Using Temp array to do so, takes O(n) time.======================
13+
14+
# def rotations(L, N, D):
15+
# temp = []
16+
17+
# for a in range(0, d):
18+
# temp.append(L[a])
19+
20+
# for a in range(0, n-d):
21+
# L[a] = L[a+d]
22+
23+
# for a in range(0, d):
24+
# L.append(temp[a])
25+
26+
# print(L)
27+
28+
29+
30+
# n=8
31+
# d=3
32+
# rotations(L, n ,d)
33+
34+
# ============ Method 2, rotate by one element at a time.==============
35+
36+
37+
def rotateLeft(arr):
38+
temp = arr[0]
39+
length = len(arr)
40+
41+
for item in range(0, length-1):
42+
arr[item] = arr[item+1]
43+
arr[item+1] = temp
44+
45+
return arr
46+
47+
48+
def rotations(arr, n):
49+
for a in range(0, n):
50+
rotateLeft(arr)
51+
printRotations(arr)
52+
53+
54+
def printRotations(arr):
55+
for a in arr:
56+
print(a,"",end = "")
57+
58+
L = [1, 2, 3, 4, 5, 6, 7, 8]
59+
rotations(L, 3)
60+
61+

0 commit comments

Comments
 (0)