-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathrotate.py
More file actions
53 lines (39 loc) · 1.28 KB
/
rotate.py
File metadata and controls
53 lines (39 loc) · 1.28 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Rotate String
Given a string and an integer k, return the string rotated by k positions
to the left. Two approaches are provided.
Reference: https://en.wikipedia.org/wiki/Circular_shift
Complexity:
Time: O(n) where n is the length of the string
Space: O(n)
"""
from __future__ import annotations
def rotate(text: str, positions: int) -> str:
"""Rotate a string left by k positions using repeated string approach.
Args:
text: The string to rotate.
positions: The number of positions to rotate left.
Returns:
The rotated string.
Examples:
>>> rotate("hello", 2)
'llohe'
"""
long_string = text * (positions // len(text) + 2)
if positions <= len(text):
return long_string[positions : positions + len(text)]
else:
return long_string[positions - len(text) : positions]
def rotate_alt(string: str, positions: int) -> str:
"""Rotate a string left by k positions using modular arithmetic.
Args:
string: The string to rotate.
positions: The number of positions to rotate left.
Returns:
The rotated string.
Examples:
>>> rotate_alt("hello", 2)
'llohe'
"""
positions = positions % len(string)
return string[positions:] + string[:positions]