LeetCode 344: Reverse String Solution

Master LeetCode problem 344 (Reverse String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

344. Reverse String

Problem Explanation

Explanation

To reverse a string in-place, we can use two pointers approach. We start with one pointer at the beginning of the array and another pointer at the end of the array. We swap the characters at these two positions and move the pointers towards the center until they meet. This way, we reverse the string in-place without using any extra memory.

  • Time complexity: O(n) where n is the length of the input string.
  • Space complexity: O(1) since we are using constant extra space.

Solution Code

class Solution {
    public void reverseString(char[] s) {
        int left = 0, right = s.length - 1;
        while (left < right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 344 (Reverse String)?

This page provides optimized solutions for LeetCode problem 344 (Reverse String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 344 (Reverse String)?

The time complexity for LeetCode 344 (Reverse String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 344 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 344 in Java, C++, or Python.

Back to LeetCode Solutions