Reverse String - Complete Solution Guide
Reverse String is LeetCode problem 344, 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
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 <= 10 5 s[i] is a printable ascii character .
Detailed Explanation
The problem asks you to reverse a string in-place. This means you cannot create a new string to store the reversed version; you must modify the original string array directly. The input is an array of characters (representing the string), and the output is the same array, but with its elements reversed. Constraints limit the string length and ensure the characters are printable ASCII characters.
Solution Approach
The solution uses a two-pointer approach. Two index variables, `left` and `right`, are initialized to point to the beginning and end of the input character array, respectively. The `while` loop continues as long as `left` is less than `right`. Inside the loop, the characters at the `left` and `right` indices are swapped. Then, `left` is incremented and `right` is decremented, moving the pointers towards the middle of the array. The loop terminates when the pointers cross, resulting in a completely reversed string.
Step-by-Step Algorithm
- Step 1: Initialize two pointers, `left` to 0 and `right` to the last index of the input array.
- Step 2: While `left` is less than `right`, swap the characters at indices `left` and `right`.
- Step 3: Increment `left` and decrement `right`.
- Step 4: Repeat steps 2 and 3 until `left` becomes greater than or equal to `right`.
- Step 5: The array `s` is now reversed in-place.
Key Insights
- Insight 1: Using two pointers, one at the beginning and one at the end of the array, allows for simultaneous swapping of elements, efficiently reversing the string in-place.
- Insight 2: In-place algorithms are crucial for memory efficiency, especially when dealing with large strings. The provided solution leverages this by only using a constant amount of extra space (O(1)).
- Insight 3: The loop condition `left < right` ensures that the middle element (if the string has an odd length) remains in place and is not swapped with itself, preventing unnecessary operations.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Two Pointers, String.
Companies
Asked at: Deutsche Bank, EPAM Systems, Garmin, Goldman Sachs, HCL, Infosys, Morgan Stanley, Odoo, tcs.