File: perform-string-shifts/solution.py

Date: 2026-06-06

Time: 18:32

perform-string-shifts/solution.py

Purpose

This file solves LeetCode 1427 — Perform String Shifts. It implements a single function that applies a sequence of left/right shift operations to a string and returns the result. This was a 30-day LeetCode challenge problem (April 2020).

Key Components

inorder(s, shift) — The sole public function. Despite the misleading name (it has nothing to do with tree traversal), it performs circular string rotation.

Patterns

Net-shift optimization: Rather than applying each shift operation sequentially (which would be O(n * totalshiftamount) with string copies), the solution collapses all operations into a single net displacement. Right shifts add, left shifts subtract. This reduces the problem to a single string slice — O(n) total regardless of how many shift operations exist.

Modular arithmetic: net %= len(s) on line 16 normalizes the displacement into [0, len(s)), handling shifts that wrap around multiple times. This also collapses negative net values into their positive equivalents via Python's floor-modulo semantics (e.g., -2 % 5 == 3).

Slice-based rotation: s[-net:] + s[:-net] on line 20 performs a right rotation by net positions using two complementary slices. This is the standard Python idiom for circular rotation.

Dependencies

Flow

1. Accumulate a net shift value: right (direction == 1) adds, left subtracts

2. Normalize via modulo to handle wraparound

3. Short-circuit if net == 0 (no-op)

4. Return the rotated string via slicing

For input s = "abcdefg", shift = [[1, 1], [1, 1], [0, 2], [1, 3]]:

Invariants

Error Handling

None. The function will raise ZeroDivisionError if s is empty (line 16). It trusts that shift entries are well-formed [int, int] pairs — no validation. This is typical for LeetCode solutions where input constraints are guaranteed by the problem.

Beliefs