search

Shifting Letters II

Jan 05, 2025 pm 10:30 PM

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 4
  • shifts[i].length == 3
  • 0 i i
  • 0 i
  • s consists of lowercase English letters.

Hint:

  1. Instead of shifting every character in each shift, could you keep track of which characters are shifted and by how much across all shifts?
  2. 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:

  1. Mark the shift boundaries: Instead of shifting each character immediately, we mark the shift effects at the start and end of each range.
  2. 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.
  3. 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

<?php /**
 * @param String $s
 * @param Integer[][] $shifts
 * @return String
 */
function shiftingLetters($s, $shifts) {
    ...
    ...
    ...
    /**
     * go to ./solution.php
     */
}

// Test the function
$s1 = "abc";
$shifts1 = [[0, 1, 0], [1, 2, 1], [0, 2, 1]];
echo shiftingLetters($s1, $shifts1) . "\n";  // Output: "ace"

$s2 = "dztz";
$shifts2 = [[0, 0, 0], [1, 1, 1]];
echo shiftingLetters($s2, $shifts2) . "\n";  // Output: "catz"
?>

Explanation:

  1. 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.
  2. After processing all the shifts, we apply a prefix sum on the shift array to get the cumulative shift at each index.
  3. Finally, we apply the cumulative shift to each character in the string.

Explanation of Code:

  1. Input Parsing: We convert the input string s into an array of characters for easier manipulation.
  2. 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.
  3. Prefix Sum: We calculate the total shift for each character by iterating over the shift array and maintaining a cumulative sum of shifts.
  4. 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.
  5. 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:

  • LinkedIn
  • GitHub

The above is the detailed content of Shifting Letters II. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version