EasyNo. 1427LeetCode Premium

Perform String Shifts — LeetCode 1427 Python Solution

Topics
Array, Math, String
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

PythonSolution
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

Time
O(n + m)where n and m are the lengths of the string s and the array shift respectively
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
2125Number of Laser Beams in a BankMedium
2575Find the Divisibility Array of a StringMedium
0043Multiply StringsMedium
0048Rotate ImageMedium
0066Plus OneEasy
0168Excel Sheet Column TitleEasy

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.

Free to download. Check it runs on your machine, then pick a plan.