Shifting Letters II
2381. Shifting Letters II
Difficulty: Medium
Topics: Array, String, Prefix Sum
You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.
Shifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z').
Return the final string after all such shifts to s are applied.
Example 1:
- Input: s = "abc", shifts = [[0,1,0],[1,2,1],[0,2,1]]
- Output: "ace"
-
Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = "zac".
- Secondly, shift the characters from index 1 to index 2 forward. Now s = "zbd".
- Finally, shift the characters from index 0 to index 2 forward. Now s = "ace".
Example 2:
- Input: s = "dztz", shifts = [[0,0,0],[1,1,1]]
- Output: "catz"
-
Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = "cztz".
- Finally, shift the characters from index 1 to index 1 forward. Now s = "catz".
Constraints:
- 1 <= s.length, shifts.length <= 5 * 104
- shifts[i].length == 3
- 0 <= starti <= endi < s.length
- 0 <= directioni <= 1
- s consists of lowercase English letters.
Hint:
- Instead of shifting every character in each shift, could you keep track of which characters are shifted and by how much across all shifts?
- Try marking the start and ends of each shift, then perform a prefix sum of the shifts.
Solution:
We need to avoid shifting the characters one by one for each shift, as this would be too slow for large inputs. Instead, we can use a more optimal approach by leveraging a technique called the prefix sum.
Steps:
- Mark the shift boundaries: Instead of shifting each character immediately, we mark the shift effects at the start and end of each range.
- Apply prefix sum: After marking all the shifts, we can compute the cumulative shifts at each character using the prefix sum technique. This allows us to efficiently apply the cumulative shifts to each character.
- Perform the shifts: Once we know the total shift for each character, we can apply the shifts (either forward or backward) to the string.
Let's implement this solution in PHP: 2381. Shifting Letters II
Explanation:
- For each shift [start, end, direction], we'll increment a shift array at start and decrement at end 1. This allows us to track the start and end of the shift range.
- After processing all the shifts, we apply a prefix sum on the shift array to get the cumulative shift at each index.
- Finally, we apply the cumulative shift to each character in the string.
Explanation of Code:
- Input Parsing: We convert the input string s into an array of characters for easier manipulation.
- Shift Array: We initialize a shift array of size n 1 to zero. This array is used to track the shift effects. For each shift [start, end, direction], we adjust the values at shift[start] and shift[end 1] to reflect the start and end of the shift.
- Prefix Sum: We calculate the total shift for each character by iterating over the shift array and maintaining a cumulative sum of shifts.
- Character Shifting: For each character in the string, we compute the final shifted character using the formula (ord(currentChar) - ord('a') totalShift) % 26, which accounts for the circular nature of the alphabet.
- Return Result: The final string is obtained by converting the character array back into a string and returning it.
Time Complexity:
- Time complexity: O(n m), where n is the length of the string s and m is the number of shifts. This is because we iterate through the string and the list of shifts once each.
- Space complexity: O(n), where n is the length of the string s, due to the space needed for the shift array.
This solution efficiently handles the problem even with the upper limits of the input constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
The above is the detailed content of Shifting Letters II. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
