Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
53 lines (39 loc) · 1.28 KB

File metadata and controls

53 lines (39 loc) · 1.28 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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]
Morty Proxy This is a proxified and sanitized view of the page, visit original site.