344. Reverse String LeetCode Solution

In this guide, you will get 344. Reverse String LeetCode Solution with the best time and space complexity. The solution to Reverse String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Reverse String solution in C++
  4. Reverse String solution in Java
  5. Reverse String solution in Python
  6. Additional Resources
344. Reverse String LeetCode Solution image

Problem Statement of Reverse String

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:

1 <= s.length <= 105
s[i] is a printable ascii character.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

344. Reverse String LeetCode Solution in C++

class Solution {
 public:
  void reverseString(vector<char>& s) {
    int l = 0;
    int r = s.size() - 1;

    while (l < r)
      swap(s[l++], s[r--]);
  }
};
/* code provided by PROGIEZ */

344. Reverse String LeetCode Solution in Java

class Solution {
  public void reverseString(char[] s) {
    int l = 0;
    int r = s.length - 1;

    while (l < r) {
      char temp = s[l];
      s[l++] = s[r];
      s[r--] = temp;
    }
  }
}
// code provided by PROGIEZ

344. Reverse String LeetCode Solution in Python

class Solution:
  def reverseString(self, s: list[str]) -> None:
    l = 0
    r = len(s) - 1

    while l < r:
      s[l], s[r] = s[r], s[l]
      l += 1
      r -= 1
# code by PROGIEZ

Additional Resources

See also  2285. Maximum Total Importance of Roads LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.