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
Perform String Shifts INPUT String s = "abc" a idx 0 b idx 1 c idx 2 Shift Matrix: [0, 1] Left shift by 1 [1, 2] Right shift by 2 0 = Left, 1 = Right Left: a-->end Right: end-->start ALGORITHM STEPS 1 Calculate Net Shift Sum all shifts with direction Left[0,1]: net = -1 Right[1,2]: net = -1 + 2 = 1 Net shift = +1 (Right) 2 Normalize Shift net = net % len(s) net = 1 % 3 = 1 3 Handle Direction Positive = right shift 4 Apply Single Shift s[-net:] + s[:-net] "abc"[-1:] + "abc"[:-1] = "c"+"ab" FINAL RESULT Original: "abc" a b c Right shift by 1 Result: "cab" c a b idx 0 idx 1 idx 2 Output: "cab" [OK] All shifts applied Key Insight: Instead of performing each shift operation individually (O(n*k)), calculate the NET shift first. Left shifts are negative, right shifts are positive. Net = sum(right) - sum(left). Then apply once! Time Complexity: O(n + k) where n = string length, k = number of shift operations TutorialsPoint - Perform String Shifts | Optimized - Calculate Net Shift
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