LeetCode 1427: Perform String Shifts Solution

Master LeetCode problem 1427 (Perform String Shifts), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1427. Perform String Shifts

Problem Explanation

Explanation:

The problem requires us to perform string shifts on a given string based on a set of shift operations. Each shift operation consists of a direction (0 for left shift, 1 for right shift) and an amount of shift. We need to apply these operations sequentially and return the final string after all shifts are performed.

To solve this problem, we can calculate the total shift amount by summing up all the shift amounts in the given operations. We can then perform the actual shift operation based on the total shift amount modulo the length of the string to handle wrap-around shifts.

Here is the step-by-step algorithm:

  1. Calculate the total shift amount by summing up all the shift amounts in the given operations.
  2. Adjust the total shift amount to ensure it is within the length of the string by taking the modulo operation with the length of the string.
  3. Perform the shift operation based on the adjusted total shift amount: if it is positive, perform a right shift; if it is negative, perform a left shift.
  4. Return the final shifted string.

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1).

:

Solution Code

class Solution {
    public String stringShift(String s, int[][] shift) {
        int totalShift = 0;
        for (int[] sh : shift) {
            totalShift += sh[0] == 0 ? -sh[1] : sh[1];
        }
        
        totalShift %= s.length();
        if (totalShift < 0) {
            totalShift += s.length();
        }
        
        return s.substring(s.length() - totalShift) + s.substring(0, s.length() - totalShift);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1427 (Perform String Shifts)?

This page provides optimized solutions for LeetCode problem 1427 (Perform String Shifts) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1427 (Perform String Shifts)?

The time complexity for LeetCode 1427 (Perform String Shifts) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1427 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1427 in Java, C++, or Python.

Back to LeetCode Solutions