Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to rotate a string of size n, n times to left in Python
Suppose we have a string s of size n. We need to find all rotated strings by rotating them 1 place, 2 places, up to n places to the left.
So, if the input is like s = "hello", then the output will be ['elloh', 'llohe', 'lohel', 'ohell', 'hello']
Approach
To solve this, we will follow these steps −
- Create an empty result list
- Get the length of the string
- For each rotation from 1 to n places:
- Move the first character to the end
- Add the rotated string to the result
- Return the result list
Example
Let us see the following implementation to get better understanding −
def solve(s):
res = []
n = len(s)
for i in range(0, n):
s = s[1:n] + s[0]
res.append(s)
return res
s = "hello"
print(solve(s))
The output of the above code is −
['elloh', 'llohe', 'lohel', 'ohell', 'hello']
How It Works
The algorithm works by repeatedly taking the first character of the string and moving it to the end. In each iteration:
- Iteration 1: "hello" ? "elloh" (move 'h' to end)
- Iteration 2: "elloh" ? "llohe" (move 'e' to end)
- Iteration 3: "llohe" ? "lohel" (move 'l' to end)
- Iteration 4: "lohel" ? "ohell" (move 'l' to end)
- Iteration 5: "ohell" ? "hello" (move 'o' to end)
Alternative Approach Using String Slicing
We can also solve this without modifying the original string by using different slice positions ?
def rotate_string(s):
n = len(s)
rotations = []
for i in range(1, n + 1):
# Rotate left by i positions
rotated = s[i:] + s[:i]
rotations.append(rotated)
return rotations
s = "hello"
print(rotate_string(s))
The output of the above code is −
['elloh', 'llohe', 'lohel', 'ohell', 'hello']
Conclusion
Both approaches generate all left rotations of a string efficiently. The first method modifies the string iteratively, while the second uses string slicing with different positions for each rotation.
