Skip to content

Commit 76e299d

Browse files
committed
Strings: rotation
1 parent 411a2cd commit 76e299d

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

src/algorithmic/arrays.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ def rotate_matrix(matrix: List[List]) -> None:
66
77
Complexity:
88
- Time: O(N^2)
9-
- Space: O(N^2)
9+
- Space: O(1)
1010
"""
1111
if len(matrix) != len(matrix[0]):
1212
raise ValueError("Input matrix must be square.")

src/algorithmic/strings.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,20 @@ def compression(string: str) -> str:
227227
return string
228228

229229
return compressed
230+
231+
232+
def rotation(s1: str, s2: str) -> str:
233+
"""Checks if string s2 is a rotation of string s1, e.g.,
234+
"erbottlewat" is a rotation of "waterbottle".
235+
236+
Complexity:
237+
- Time: O(A + B)
238+
- Space: O(A + B)
239+
240+
Where A, B are the lengths of s1 and s2, respectively,
241+
assuming sub-string check has O(A + B) time.
242+
"""
243+
if len(s1) != len(s2) or len(s1) == 0:
244+
return False
245+
246+
return s1 in ''.join([s2, s2])

tests/test_strings.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,11 @@ def test_compression():
7575
assert strings.compression("AABCCCCCAAA") == "A2B1C5A3"
7676
assert strings.compression("ABBACCC") == "A1B2A1C3"
7777
assert strings.compression("AA") == "AA"
78+
79+
80+
def test_rotation():
81+
assert strings.rotation("waterbottle", "erbottlewat")
82+
assert not strings.rotation("waterbottle", "notarotation")
83+
84+
assert not strings.rotation("waterbottle", "w")
85+
assert not strings.rotation("", "")

0 commit comments

Comments
 (0)