Perform String Shifts — LeetCode 1427 Python Solution
- Problem
- #1427
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "abc", shift = [[0,1],[1,2]]
- Output
- "cab"
- Explanation
- [0,1] means shift to left by 1. "abc" -> "bca"
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
| Measure | Complexity |
|---|---|
| Time | O(n + m), where n and m are the lengths of the string s and the array shift respectively |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1427. Perform String Shifts is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1427. Perform String Shifts?
- LeetCode 1427. Perform String Shifts is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1427. Perform String Shifts?
- The Python solution on this page runs in O(n + m), where n and m are the lengths of the string s and the array shift respectively.
- What is the space complexity of LeetCode 1427. Perform String Shifts?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1427. Perform String Shifts cover?
- LeetCode 1427. Perform String Shifts is tagged Array, Math and String on LeetCode.
- Is LeetCode 1427. Perform String Shifts a premium problem?
- Yes. LeetCode 1427. Perform String Shifts is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.