LeetCode Python/Java/C++/JS  >  Array  >  344. Reverse String  >  Solved in Java, Python, C++, JavaScript, C#, Go, Ruby  >  GitHub or Repost

LeetCode link: 344. Reverse String, difficulty: Easy.

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: s = ["h","e","l","l","o"]

Output: ["o","l","l","e","h"]

Example 2:

Input: s = ["H","a","n","n","a","h"]

Output: ["h","a","n","n","a","H"]

Constraints:

Hint 1

The entire logic for reversing a string is based on using the opposite directional two-pointer approach!

Intuition

Webmaster (Zhang Jian): πŸ‘‹

Hi everyone! I am Zhang Jian.
I know the challenge of transitioning from mastering algorithms to actually landing a great job. That's why, in addition to this resource, I personally developed leader.me!

πŸš€ leader.me is the ultimate all-in-one platform for programmers to build their personal brand, featuring portfolio hosting, resume builders, and integrated blogs.

Build your programmer brand at leader.me β†’


  1. This problem can be solved in one line of code using the built-in sort() method of the programming language. If this question is asked in an interview, the questioner should be testing how to do it without the built-in method.
  2. Use two pointers with opposite directions, initially one pointer points to the index 0 and the other pointer points to the index s.length - 1.
  3. Traverse the elements of the array, and the loop condition is while (left < right). In the loop body, left += 1, right -= 1.
  4. In the loop body, swap the two values.
  5. The above is the template for two pointers in opposite directions.

Step-by-Step Solution

  1. Use two pointers with opposite directions, initially one pointer points to the index 0 and the other pointer points to the index s.length - 1.

    left = 0
    right = s.length - 1
    
  2. Traverse the elements of the array, and the loop condition is while (left < right). In the loop body, left += 1, right -= 1.

    left = 0
    right = s.length - 1
    
    while left < right # 1
      left += 1 # 2
      right -= 1 # 3
    end
    
  3. In the loop body, swap the two values.

    left = 0
    right = s.length - 1
    
    while left < right
      s[left], s[right] = s[right], s[left] # 1
    
      left += 1
      right -= 1
    end
    

Complexity

Time complexity

O(N)

Space complexity

O(1)

Java #

class Solution {
    public void reverseString(char[] s) {
        var left = 0;
        var right = s.length - 1;

        while (left < right) {
            var leftValue = s[left];
            s[left] = s[right];
            s[right] = leftValue;

            left++;
            right--;
        }
    }
}

Python #

class Solution:
    def reverseString(self, s: List[str]) -> None:
        left = 0
        right = len(s) - 1

        while left < right:
            s[left], s[right] = s[right], s[left]
            left += 1
            right -= 1

C++ #

class Solution {
public:
    void reverseString(vector<char>& s) {
        auto left = 0;
        auto right = s.size() - 1;

        while (left < right) {
            swap(s[left], s[right]);

            left++;
            right--;
        }
    }
};

JavaScript #

var reverseString = function (s) {
  let left = 0
  let right = s.length - 1

  while (left < right) {
    [s[left], s[right]] = [s[right], s[left]]

    left++
    right--
  }
};

C# #

public class Solution
{
    public void ReverseString(char[] s)
    {
        int left = 0;
        int right = s.Length - 1;

        while (left < right)
        {
            (s[left], s[right]) = (s[right], s[left]);

            left++;
            right--;
        }
    }
}

Go #

func reverseString(s []byte)  {
    left := 0
    right := len(s) - 1

    for left < right {
        s[left], s[right] = s[right], s[left]

        left++
        right--
    }
}

Ruby #

def reverse_string(s)
  left = 0
  right = s.size - 1

  while left < right
    s[left], s[right] = s[right], s[left]

    left += 1
    right -= 1
  end
end

Other languages

Welcome to contribute code to LeetCode.blog GitHub -> 344. Reverse String. Thanks!

Level Up Your Developer Identity

πŸš€ While mastering algorithms is key, showcasing your talent is what gets you hired.
We recommend leader.me β€” the ultimate all-in-one personal branding platform for programmers.

The All-In-One Career Powerhouse:

  • πŸ“„ Resume, Portfolio & Blog: Integrate your skills, projects, and writing into one stunning site.
  • 🌐 Free Custom Domain: Bind your own personal domain for freeβ€”forever.
  • ✨ Premium Subdomains: Stand out with elite tech handle like name.leader.me.

Build Your Programmer Brand at leader.me β†’