Reverse Only Letters - Complete Solution Guide
Reverse Only Letters is LeetCode problem 917, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given a string s , reverse the string according to the following rules: All the characters that are not English letters remain in the same position. All the English letters (lowercase or uppercase) should be reversed. Return s after reversing it . Example 1: Input: s = "ab-cd" Output: "dc-ba" Example 2: Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Example 3: Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!" Constraints: 1 <= s.length <= 100 s consists of characters with ASCI
Detailed Explanation
The problem asks us to reverse only the English letters within a given string while keeping all other characters (non-letters) in their original positions. The input is a string `s`, and the output should be a modified string where the letters are reversed. Constraints include the string length being between 1 and 100, characters having ASCII values between 33 and 122, and no quotation marks or backslashes.
Solution Approach
The Java, C, and C++ solutions use a two-pointer approach to reverse the letters in-place. The Python solution first extracts the letters into a separate list, reverses the list, and then rebuilds the string by iterating through the original string and replacing letters with the reversed letters, keeping other characters in their original positions. The core idea is to maintain two pointers, one at the beginning and one at the end of the string. Move the pointers inwards, skipping non-letter characters until both pointers point to letters. Then, swap the letters and continue the process until the pointers meet.
Step-by-Step Algorithm
- Step 1: Initialize two pointers, `left` to 0 and `right` to `s.length() - 1`.
- Step 2: While `left` is less than `right`:
- Step 3: Move `left` to the right until `s[left]` is an alphabetic character or `left >= right`.
- Step 4: Move `right` to the left until `s[right]` is an alphabetic character or `left >= right`.
- Step 5: If `left` is still less than `right`, swap `s[left]` and `s[right]`, increment `left`, and decrement `right`.
- Step 6: After the loop finishes, return the modified string.
Key Insights
- Insight 1: Recognize that only alphabetic characters need to be reversed, preserving the positions of non-alphabetic characters.
- Insight 2: Utilize a two-pointer approach for in-place reversal (in some language implementations) or a separate data structure to store letters and then rebuild the string.
- Insight 3: The `isalpha()` function is crucial for efficiently identifying alphabetic characters.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Two Pointers, String.
Companies
Asked at: Snowflake, Turing, Zoho.