The Indian Engineer

Problem 344 Reverse String

Posted on Last edited 1 min

Two-Pointer String

Problem Statement

Link - Problem 344

Question

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

Solution

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

Complexity Analysis

Explanation

1. Intuition

2. Implementation

  1. Initialize two pointers start and end to 0 and s.size()-1 respectively.
  2. Swap the elements at start and end index.
  3. Increment start and decrement end until start is less than end.

Alternate Solution

class Solution {
public:
    void reverseString(vector<char>& s) {
        reverse(s.begin(),s.end());
    }
};

Complexity Analysis

Explanation


Utilizes the two pointer approach to swap the elements in the array.