Perform String Shifts — LeetCode 1427 Python Solution

EasyLeetCode PremiumArrayMathString
Problem
#1427
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n + m), where n and m are the lengths of the string s and the array shift respectively
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview