Perform String Shifts - Problem
String Shifting Challenge
You're tasked with implementing a string rotation system! Given a string
Each shift operation is defined by a direction and amount:
โข Left shift (0): Remove characters from the beginning and append them to the end
โข Right shift (1): Remove characters from the end and prepend them to the beginning
For example, left shifting
Think of it like a circular array where characters wrap around!
You're tasked with implementing a string rotation system! Given a string
s containing lowercase English letters and a series of shift operations, you need to perform all the transformations and return the final result.Each shift operation is defined by a direction and amount:
โข Left shift (0): Remove characters from the beginning and append them to the end
โข Right shift (1): Remove characters from the end and prepend them to the beginning
For example, left shifting
"abcde" by 2 gives "cdeab", while right shifting by 2 gives "deabc".Think of it like a circular array where characters wrap around!
Input & Output
example_1.py โ Basic Left and Right Shifts
$
Input:
s = "abc", shift = [[0,1],[1,2]]
โบ
Output:
"cab"
๐ก Note:
Left shift by 1: "abc" โ "bca". Then right shift by 2: "bca" โ "abc" โ "cab". Alternatively, net shift = 1 - 2 = -1 (right shift by 1), so "abc" โ "cab".
example_2.py โ Multiple Operations
$
Input:
s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
โบ
Output:
"efgabcd"
๐ก Note:
Net shift calculation: right(-1) + right(-1) + left(+2) + right(-3) = -1-1+2-3 = -3. Right shift by 3 is equivalent to left shift by 4. So we get s[4:] + s[:4] = "efg" + "abcd" = "efgabcd".
example_3.py โ Large Shifts with Modulo
$
Input:
s = "xqgwkiqpif", shift = [[1,4],[0,7],[0,8],[0,7],[0,6],[1,3],[0,1],[1,7],[0,5],[0,6]]
โบ
Output:
"qpifxqgwki"
๐ก Note:
With large shift amounts, we use modulo arithmetic. Net shift = -4+7+8+7+6-3+1-7+5+6 = 26. Since string length is 10, effective shift = 26 % 10 = 6. Result: s[6:] + s[:6].
Constraints
- 1 โค s.length โค 100
- s only contains lower case English letters
- 1 โค shift.length โค 100
- shift[i].length = 2
- 0 โค shift[i][0] โค 1
- 0 โค shift[i][1] โค 100
Visualization
Tap to expand
Understanding the Visualization
1
Circular Layout
Visualize string characters arranged in a circle
2
Calculate Net Movement
Combine all left/right operations into single rotation
3
Efficient Slicing
Use string slicing to achieve rotation in O(n) time
Key Takeaway
๐ฏ Key Insight: Instead of performing each shift operation individually, calculate the total net shift and perform one efficient string slicing operation, reducing complexity from O(n ร shifts) to O(n + operations).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code