Solving Leetcode Interviews in Seconds with AI: Reverse String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "344" 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
Write a function that reverses a string. The input string is given as an array of characters s. You must do this by modifying the input array in-place with O(1) extra memory. Example 1: Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"] Example 2: Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"] Constraints: 1 <= s.length <= 105 s[i] is a printable ascii character.
Explanation
Here's the breakdown of the solution:
- Two-Pointer Approach: Use two pointers, one starting from the beginning of the array and the other from the end.
- In-place Swap: Swap the characters pointed to by the two pointers.
Move Pointers: Move the start pointer one step forward and the end pointer one step backward until they meet in the middle.
Runtime Complexity: O(n), where n is the length of the string. Storage Complexity: O(1).
Code
def reverseString(s: list[str]) -> None:
"""Reverses a string in-place.
Args:
s: The input string as a list of characters.
"""
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1