344 Reverse String

344 Reverse String

Techniques Used

  • Binary Search

Difficulty Level

  • Easiest

Approach

  • Take two pointers (variables), one will point to start, and other end to the last element of char array.
  • Now, while start < end
    • Swap both the characters
    • Increment start and decrement end.

Complexity:

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

Code: C++


class Solution {
public:
    void reverseString(vector<char>& s) {

        int start = 0;
        int end = s.size() - 1;

        while(start < end){

            swap(s[start], s[end]);

            start++;
            end--;

        }

        return;

    }
};

Code: Java


class Solution {
    public void reverseString(char[] s) {

        int start = 0;
        int end = s.length - 1;

        while(start < end){

            char temp = s[start];

            s[start] = s[end];
            s[end] = temp;

            start++;
            end--;

        }

        return;

    }
}