Java O(n) Simple Solution that Interviewers Are Looking For

  • 0

    If you get asked this, you're expected to deal with arrays and do some basic character swapping logic.

    Time Complexity
    The time complexity is O(n), where n is the number of characters in our string s, since the for loop iterates through n/2 characters.

    class Solution {
        public String reverseString(String s) {
            char [] ch = s.toCharArray();
            for (int i = 0; i < ch.length/2; i++) {
               // Swap characters
                char tmp = ch[i];
                ch[i] = ch[ch.length - 1 - i];
                ch[ch.length - 1 - i] = tmp;
            return new String(ch);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.