Solving Leetcode Interviews in Seconds with AI: Reverse Only Letters
Introduction
In this blog post, we will explore how to solve the LeetCode problem "917" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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 ASCII values in the range [33, 122]. s does not contain '\"' or '\'.
Explanation
Here's a solution to the string reversal problem, focusing on efficiency and clarity.
- Two-Pointer Approach: Use two pointers,
leftandright, initialized to the start and end of the string, respectively. - Conditional Swapping: Move the pointers inwards, skipping non-letter characters. When both pointers point to letters, swap them.
In-place Modification: Modify the string in-place to avoid extra space usage.
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1) (in-place modification).
Code
def reverse_only_letters(s: str) -> str:
"""
Reverses the English letters in a string while keeping other characters in place.
"""
s_list = list(s) # Convert string to list for in-place modification
left, right = 0, len(s) - 1
while left < right:
if not s_list[left].isalpha():
left += 1
elif not s_list[right].isalpha():
right -= 1
else:
s_list[left], s_list[right] = s_list[right], s_list[left]
left += 1
right -= 1
return "".join(s_list) # Convert list back to string