
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.
1public class 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}
13A straightforward two-pointer implementation, where a temp variable helps in swapping characters until the middle is reached.
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.
1#include
Recursive function in C swaps characters starting from outermost towards the middle, reducing the problem size in each call.