Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

344. Reverse String 🌟

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

O(N) time and O(1) space, using stack

O(N) Time , recursive

class Solution{
public:
    void reverseString(vector<char> &s, int i = 0){
        int n = s.size();
        if (i == n / 2) return;

        swap(s[i], s[n - 1 - i]);
        reverseString(s, i + 1);
    }
};

O(N) Time two pointer solution

Code

class Solution {
public:
    void reverseString(vector<char>& s) {
        int l=0,r=s.size()-1;
        while(l<r){
            swap(s[l++],s[r--]);
        }
    }
};