Leetcode #1427: Perform String Shifts
In this guide, we solve Leetcode #1427 Perform String Shifts in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Array, Math, String
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: s = "abc", shift = [[0,1],[1,2]]
Output: "cab"
Explanation:
[0,1] means shift to left by 1. "abc" -> "bca"
[1,2] means shift to right by 2. "bca" -> "cab"
Python Solution
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
x = sum((b if a else -b) for a, b in shift)
x %= len(s)
return s[-x:] + s[:-x]
Complexity
The time complexity is , where and are the lengths of the string and the array respectively. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.