Posts Reverse String
Post
Cancel

Reverse String

Problem Description

Given a character array, reverse it.
Reverse String

Solution

We can use recursion for this, although it will not be O(1) space complexity. The other approach is to use two pointers - front and back. Each time swap the two elements and keep moving to the inner elements.

Recursive Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
    public void reverseString(char[] s) {        
        if(s.length <= 1) return;
        reverseStringX(s, 0, s.length-1);
    }
    
    public void reverseStringX(char[] s, int start, int end) {
        
        if(start>=end) return;
        
        char temp = s[start];
        s[start] = s[end];
        s[end] = temp;
        
        reverseStringX(s, start+1, end-1);
        
    }
}
This post is licensed under CC BY 4.0 by the author.