
Sponsored
Sponsored
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.
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.
1class Solution {
2 public void reverseString(char[] s) {
3 int left = 0, right = s.length - 1;
4 while (left < right) {
5 char temp = s[left];
6 s[left] = s[right];
7 s[right] = temp;
8 left++;
9 right--;
10 }
11 }
12}
13The Java code uses a similar two-pointer strategy with a temporary variable for swapping characters. It is simple and operates in O(n) time complexity.
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.
Time Complexity: O(n).
Space Complexity: O(n) due to call stack depth.
1public class Solution {
2 private void ReverseUtil(char[] s, int left, int right) {
if (left >= right) return;
char temp = s[left];
s[left] = s[right];
s[right] = temp;
ReverseUtil(s, left + 1, right - 1);
}
public void ReverseString(char[] s) {
ReverseUtil(s, 0, s.Length - 1);
}
}
C# recursively swaps the elements relying on a helper method capturing the left and right indices. It presents compact and recursive in-place reversal.