Perform String Shifts - Problem

You are given a string s containing lowercase English letters, and a matrix shift, where shift[i] = [directioni, amounti]:

  • directioni can be 0 (for left shift) or 1 (for right shift).
  • amounti is the amount by which string s is to be shifted.

A left shift by 1 means remove the first character of s and append it to the end. Similarly, a right shift by 1 means remove the last character of s and add it to the beginning.

Return the final string after all operations.

Input & Output

Example 1 — Basic Mixed Shifts
$ Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
💡 Note: Left shift by 1: "abc" → "bca". Right shift by 2: "bca" → "abc" → "cab". Final result is "cab".
Example 2 — Only Right Shifts
$ Input: s = "abcdefg", shift = [[1,1],[1,1],[0,2],[1,3]]
Output: "efgabcd"
💡 Note: Net shift calculation: +1 +1 -2 +3 = +3 right shifts. Final result moves last 3 characters to front.
Example 3 — Shifts Cancel Out
$ Input: s = "hello", shift = [[0,2],[1,2]]
Output: "hello"
💡 Note: Left shift by 2 and right shift by 2 cancel out. Net shift is 0, so string remains unchanged.

Constraints

  • 1 ≤ s.length ≤ 100
  • s only contains lower case English letters
  • 1 ≤ shift.length ≤ 100
  • shift[i].length == 2
  • 0 ≤ direction ≤ 1
  • 0 ≤ amount ≤ 100

Visualization

Tap to expand
String Shifts: Rotate Left or RightInput StringabcShift Operations[0,1] Left[1,2] RightNet Effect: -1 + 2 = +1 (Right Shift)Rotate Right by 1Result StringcabLeft Shift: Move first char to endRight Shift: Move last char to frontFinal: "abc" → "cab"Efficient: Calculate net shift, then rotate once!
Understanding the Visualization
1
Input
String s and array of shift operations [direction, amount]
2
Process
Calculate net shift and perform single rotation
3
Output
Rotated string after all operations
Key Takeaway
🎯 Key Insight: Multiple shift operations can be combined into a single net rotation using modular arithmetic
Asked in
Facebook 15 Amazon 8
25.0K 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