Reverse String

Changing from install and configuring server products to some coding.

Let’s reverse a char array.

Input: [“a”, “b”, “c”, “d”, “e”, “f”]
Output: [“f”, “e”, “d”, “c”, “b”, “a”]

I’m writing the code in Java.

    public void reverseString(char[] s) {
        int i = 0;
        int j = s.length - 1;
        while (i < j)
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;

This algorithm is probably O(n) in time complexity and O(1) in space complexity as it does not create another set of array to store the result.

Just a little bit of fun of coding. 🙂

Leave a Reply

Your email address will not be published.