Reverse String

Solution For Reverse String

Problem Description:
Given a string s, return the string reversed.

Example 1:
Input: s = “hello”
Output: “olleh”

Example 2:
Input: s = “world”
Output: “dlrow”

Approach:
The idea is to swap the first and last character of the string, then move towards the middle of the string, swapping the characters on the left and right side. We can use two pointers for this.

Algorithm:
1. Initialize two pointers, one at the start and the other at the end of the string.
2. Swap the characters at the two pointers.
3. Move the left pointer towards the right side of the string.
4. Move the right pointer towards the left side of the string.
5. Repeat the above two steps until the pointers cross each other.

Code:

class Solution {
public:
string reverseString(string s) {
int n = s.length();
int left = 0, right = n – 1;
while (left < right) {
swap(s[left], s[right]);
left++;
right–;
}
return s;
}
};

Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as we are not using any extra memory to store characters.

Step by Step Implementation For Reverse String

public class Solution {
    public String reverseString(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i = s.length() - 1; i >= 0; i--) {
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}
class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        # return s[::-1]
        
        # Or
        
        start = 0
        end = len(s) - 1
        s = list(s)
        while start < end:
            s[start], s[end] = s[end], s[start]
            start += 1
            end -= 1
        return ''.join(s)
var reverseString = function(s) {
    let left = 0
    let right = s.length - 1
    
    while (left < right) {
        //swap characters at left and right indices
        [s[left], s[right]] = [s[right], s[left]]
        //move indices towards the center
        left++
        right--
    }
    
    return s
};
class Solution {
public:
    string reverseString(string s) {
        string result = "";
        for(int i = s.size() - 1; i >= 0; i--) {
            result += s[i];
        }
        return result;
    }
};
public class Solution { 
    public string ReverseString(string s) { 
        //check for empty string 
        if (s == "") { 
            return s; 
        } 
          
        //convert string to char array 
        char[] array = s.ToCharArray(); 
          
        //iterate through the array in reverse order and add characters to a new string 
        string reverse = ""; 
        for (int i = array.Length - 1; i >= 0; i--) { 
            reverse += array[i]; 
        } 
          
        //return the reversed string 
        return reverse; 
    } 
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]