Perform String Shifts - Problem
String Shifting Challenge

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
String as Circular ArrayabcdeLeft ShiftRight ShiftNet Shift CalculationOperations: [[0,2], [1,1], [0,1]]Left shifts: 2 + 1 = 3Right shifts: 1Net: 3 - 1 = 2 (left)Normalized: 2 % 5 = 2Result: s[2:] + s[:2]"abcde"[2:] + "abcde"[:2] = "cdeab"Before: "abcde"abcdeAfter: "cdeab"cdeabโšก Key Insight: Multiple operations = Single rotation with net shift amount
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).
Asked in
Meta 15 Amazon 12 Microsoft 8 Google 6
28.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen