Skip to content

Commit 33e5c5a

Browse files
committed
4.rotate an array and test case
1 parent 99700f8 commit 33e5c5a

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# 4.rotate an array
2+
# Reversal Algorithm(best approach)
3+
def rotateArr(arr, d):
4+
n = len(arr)
5+
d %= n
6+
7+
def reversal(arr, start, end):
8+
while start < end:
9+
arr[start], arr[end] = arr[end], arr[start]
10+
start += 1
11+
end -= 1
12+
return arr
13+
14+
reversal(arr, 0, d - 1)
15+
reversal(arr, d, n - 1)
16+
reversal(arr, 0, n - 1)
17+
return arr
18+
19+
20+
# T.C = O(n)
21+
# S.C = O(1)
22+
23+
24+
def rotateArr(arr, d):
25+
n = len(arr)
26+
d = d % n
27+
return arr[d:] + arr[:d]
28+
29+
30+
# T.C = O(n)
31+
# S.C = O(n)
32+
33+
34+
def rotateArr(arr, d):
35+
n = len(arr)
36+
temp = []
37+
for i in range(d, n):
38+
temp.append(arr[i])
39+
for j in range(0, d):
40+
temp.append(arr[j])
41+
return temp
42+
43+
44+
# T.C = O(n)
45+
# S.C = O(n)
46+
47+
48+
def rotateArr(arr, d):
49+
n = len(arr)
50+
first = 0
51+
for i in range(d):
52+
first = arr[0]
53+
for j in range(n - 1):
54+
arr[j] = arr[j + 1]
55+
arr[n - 1] = first
56+
return arr
57+
58+
59+
# T.C = O(d*n)
60+
# S.C = O(1)
61+
62+
print(rotateArr([1, 2, 3, 4, 5], 2))

test/test_case.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
sys.path.append(os.path.abspath(".."))
55
from geek_for_geeks.challenge.move_zero import pushZerosToEnd
66
from geek_for_geeks.challenge.reverse_an_array import reverseArray
7+
from geek_for_geeks.challenge.rotate_an_array import rotateArr
78
from geek_for_geeks.challenge.secondlargest import getSecondLargest
89

910

@@ -93,3 +94,25 @@ def test_palindrome_list(self):
9394
arr = [1, 2, 3, 2, 1]
9495
expected = [1, 2, 3, 2, 1]
9596
assert reverseArray(arr) == expected
97+
98+
99+
class TestRotateArr:
100+
def test_rotate_by_two(self):
101+
arr = [1, 2, 3, 4, 5]
102+
rotated = rotateArr(arr, 2)
103+
assert rotated == [3, 4, 5, 1, 2]
104+
105+
def test_rotate_by_zero(self):
106+
arr = [1, 2, 3]
107+
rotated = rotateArr(arr, 0)
108+
assert rotated == [1, 2, 3]
109+
110+
def test_rotate_by_length(self):
111+
arr = [1, 2, 3]
112+
rotated = rotateArr(arr, 3)
113+
assert rotated == [1, 2, 3]
114+
115+
def test_rotate_by_more_than_length(self):
116+
arr = [1, 2, 3, 4]
117+
rotated = rotateArr(arr, 6) # 6 % 4 = 2
118+
assert rotated == [3, 4, 1, 2]

0 commit comments

Comments
 (0)