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 <= 105s[i] is a printable ascii character.The two-pointer technique involves using two pointers, one starting at the beginning of the array and the other at the end. Swap the characters at the two pointers and then move the pointers inwards towards each other until they meet or cross. This method efficiently reverses the array in-place with O(1) extra space.
The C solution uses a while loop with two pointers, left and right, to swap the characters until the entire string is reversed. The process continues until the left pointer is not less than the right pointer.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) where n is the number of characters in the string.
Space Complexity: O(1) as it uses a fixed amount of extra space.
This approach uses recursion to swap characters at symmetric positions while visually simplifying the problem. The base case is when the left index is not less than the right index.
Recursive function in C swaps characters starting from outermost towards the middle, reducing the problem size in each call.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n).
Space Complexity: O(n) due to call stack depth.
| Approach | Complexity |
|---|---|
| Two-Pointer Approach | Time Complexity: O(n) where n is the number of characters in the string. |
| Recursive Approach | Time Complexity: O(n). |
How to get "Constant Space" Algorithms in Coding Interviews | Reverse String - Leetcode 344 • Greg Hogg • 328,465 views views
Watch 9 more video solutions →Practice Reverse String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor